How to handle different entity types? - oop

I am wondering how to approach the use case that I need different types of an entity. In my case, I want to create an Approval-Entity. Yet there are different kinds of approvals I have to tell apart.
I am wondering if I should create a type field and then handle the different types via type constants that I also store in the database, e.g.:
use Doctrine\ORM\Mapping as ORM;
/**
* Approval
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Hn\AssetDbBundle\Entity\ApprovalRepository")
*/
class Approval
{
const SOME_TYPE = 1;
const SOME_OTHER_TYPE = 2;
/**
* #var integer
* #ORM\Column(name="type", type="integer")
*/
private $type;
}
Another approach would be to make my Approval Entity abstract then extend SomeTypeApproval and SomeOtherTypeApproval from it. This seems like a more OOP solution to me but as the question should imply, I am somewhat unsure.
So I am wondering what the up- and downsides of each approach are in order to decide which route I should follow.

I would say that it's a bit overkill to create different Types of Entities for basically the same thing.
I had something similiar, i needed a way to tell a Entity which Type of Entity it is.
I just created another Entity "EntityType", where i stored all Types in the Database and just flaged the Entity with the id of the Type.
So your 2 Entities would be
use Doctrine\ORM\Mapping as ORM;
/**
* Approval
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Hn\AssetDbBundle\Entity\ApprovalRepository")
*/
class Approval
{
/**
* #var integer
* ManyToOne Relation to "ApprovalType"
*/
private $type;
}
And the ApprovalType
/**
* ApprovalType
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Hn\AssetDbBundle\Entity\ApprovalTypeRepository")
*/
class ApprovalType
{
//Here you can define the type
private $name;
//OneToMany Relationship to the Approvals
private $approvals;
}
Working perfectly for me and i think it suites the case pretty well and is the perfect mix of OOP and "keep it simple"

In order to differentiate the types, I followed up the object oriented path. I introduced a BaseApproval class which has all the shared fields:
<?php
namespace My\Bundle\\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContextInterface;
/**
* #ORM\Entity
* #ORM\Table()
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({
* "someType" = "My\Bundle\Entity\Approvals\SomeTypeApproval",
* "someOtherType" = "My\Bundle\Entity\Approvals\SomeOtherTypeApproval",
* "yetAnotherType" = "My\Bundle\Entity\Approvals\YetAnotherTypeApproval"
* })
*/
abstract class BaseApproval
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="textField", type="text", nullable=true)
*/
private $textField;
...
}
The types are only some basic classes in my case, as there are no type specific fields:
<?php
namespace My\Bundle\Entity\Approvals;
use Doctrine\ORM\Mapping as ORM;
use My\Bundle\Entity\BaseApproval;
/**
* #ORM\Entity
*/
class SomeTypeApproval extends BaseApproval
{
}
I went with single table inheritance as the different types share the same fields and it is unlikely that this will change much. Yet even if one type were to get additional fields, I could then define them in its entity class alone without polluting the other types. (On the database side, all types will have the same fields, those that aren't defined for all will be nulled).
I preferred this approach as I have the ability to typehint the approvals when I add them to an entity or could easily attach an listener to them without manually checking some field.

Related

How to define a Doctrine mappedSuperclass using XML or YAML instead of annotation mapping

The following script comes from https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/inheritance-mapping.html#mapped-superclasses, and was only changed to include a second sub-class. It is my understanding that MappedSuperclassBase cannot exist by itself but must be extended by one and only one sub-class (i.e. either EntitySubClassOne or EntitySubClassTwo), and is the same concept as supertype/subtype for SQL. Agree?
How is a super/sub type defined using either YAML or XML instead of annotation mapping?
<?php
/** #MappedSuperclass */
class MappedSuperclassBase
{
/** #Column(type="integer") */
protected $mapped1;
/** #Column(type="string") */
protected $mapped2;
/**
* #OneToOne(targetEntity="MappedSuperclassRelated1")
* #JoinColumn(name="related1_id", referencedColumnName="id")
*/
protected $mappedRelated1;
// ... more fields and methods
}
/** #Entity */
class EntitySubClassOne extends MappedSuperclassBase
{
/** #Id #Column(type="integer") */
private $id;
/** #Column(type="string") */
private $name;
// ... more fields and methods
}
/** #Entity */
class EntitySubClassTwo extends MappedSuperclassBase
{
/** #Id #Column(type="integer") */
private $id;
/** #Column(type="string") */
private $name;
// ... more fields and methods
}
Based on our comments, I think I see your confusion. Because the docs handle both "MappedSuperclass" and "Discriminator" on the same page, I think you've mixed up their uses in your head. Hopefully this can help you:
A MappedSuperclass provides properties/defaults in a re-usable way, but it can never be an Entity by itself. This is comparable to PHP's abstract classes (which cannot be instantiated on their own)
A Discriminator provides the ability to "extend" an Entity, making it another Entity. For example, having a Person Entity gives you 1 Entity. This Entity can be extended, for example by Worker and Manager.
A good use-case for a MappedSuperclass would be an AbstractEntity. Every Entity needs an ID, a unique identifier. It also gives you something common to check against in Listeners and such. So, go ahead and create:
/**
* #ORM\MappedSuperclass
*/
abstract class AbstractEntity
{
/**
* #var int
* #ORM\Id
* #ORM\Column(name="id", type="integer", options={"unsigned":true})
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
// getter / setter
}
See how this is both declared abstract and MappedSuperclass?
This is because neither (abstract class and MappedSuperclass) cannot be instantiated on their own. You cannot do $entity = new AbstractEntity() because it's an abstract PHP class. Neither will Doctrine create a separate table for AbstractEntity.
Next, create a Person:
/**
* #ORM\Entity
* #ORM\Table(name="persons")
*
* #InheritanceType("JOINED")
* #DiscriminatorColumn(name="discr", type="string")
*/
class Person extends AbstractEntity
{
/**
* #var string
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
protected $name;
// getter / setter
}
The above, Person, Entity is setup for Class Table Inheritance through the JOINED inheritance type. Meaning that, on the database level, the table persons will be separate from any columns added by other entities, extending Person.
Notice how I did not declare DiscriminatorMap. Below from the docs, highlighted in bold by me:
Things to note:
The #InheritanceType, #DiscriminatorColumn and #DiscriminatorMap must be specified on the topmost class that is part of the mapped entity hierarchy.
The #DiscriminatorMap specifies which values of the discriminator column identify a row as being of which type. In the case above a value of "person" identifies a row as being of type Person and "employee" identifies a row as being of type Employee.
The names of the classes in the discriminator map do not need to be fully qualified if the classes are contained in the same namespace as the entity class on which the discriminator map is applied.
If no discriminator map is provided, then the map is generated automatically. The automatically generated discriminator map contains the lowercase short name of each class as key.
Now, let's create a Worker:
/**
* #ORM\Entity
* #ORM\Table(name="workers")
*/
class Worker extends Person
{
/**
* #var int
* #ORM\Column(name="worker_id", type="integer", length=11, nullable=false)
*/
protected $workerId;
// getter / setter
}
So, now we've got:
MappedSuperclass: AbstractEntity - is not a stand-alone Entity
Discriminated: Person - is a stand-alone Entity
"normal": Worker - extends Person
Things to note:
A MappedSuperclass can not be instantiated. As such: you can not create links/relations to it. Comparable with PHP's abstract class
A Discriminated Entity is one which also stands alone and can be used as a normal Entity. You can create relations to and from it, without an issue
An Entity extending a Discriminated Entity is an instance of both. In the above code these are both true: $worker instanceof Worker and $worker instanceof Person, because the Worker extends Person. However, $person instanceof Worker will be false!
$workerId = $person->getWorkerId() // generates "method does not exist" fatal
$workerId = $worker->getWorkerId() // generates integer value
Hope that managed to clear stuff up for you. If not, feel free to ask.

Entities Mapping

i get this error in the Entities Mapping
The association EventBundle\Entity\Articles#comentaires refers to the owning side field EventBundle\Entity\Articles#Commentaire which does not exist.
So in the entity Articles ->
/**
* #ORM\OneToMany(targetEntity="Articles", mappedBy="Commentaire")
*/
private $comentaires;
ANd The entity Commentaire
/**
* #ORM\ManyToOne(targetEntity="Articles", inversedBy="Commentaire")
* #ORM\JoinColumn(name="article_id", nullable=true)
*/
private $articles;
It's because you write "$comentaires" instead of "$commentaires" :)
And I think your annotations are false. You should write :
#ORM\OneToMany(targetEntity="Commentaire", mappedBy="Articles")

Mapped Super Class Symfony2.2

I have created a Bundle (called MYBUNDLE) with just 2 entities: Menu and Group. Both were declared as mappedSuperclass because I need this bundle could be use for other projects. As a condition, projects will have to extend from these classes to customize them by setting the tables name or adding some fields. For instance:
Classes into MYBUNDLE:
class Group{
protected $id;
protected $menus;
}
class Menu{
protected $id;
protected $groups;
}
YML for mapping my entities from MYBUNDLE
Project\MYBUNDLE\Entity\Menu:
type: mappedSuperclass
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
Project\MYBUNDLE\Entity\Group:
type: mappedSuperclass
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
manyToMany:
menus:
targetEntity: Menu
joinTable:
name: sf_group_menu
joinColumns:
sf_group_id:
referencedColumnName: id
inverseJoinColumns:
sf_menu_id:
referencedColumnName: id
Classes into my child bundle:
use Project\MYBUNDLE\Entity\Group as TGroup;
/**
* #ORM\Entity
* #ORM\Table(name="sf_group")
*/
class Group extends TGroup
{ }
use Project\MYBUNDLE\Entity\Menu as TMenu;
/**
* #ORM\Entity
* #ORM\Table(name="sf_menu")
*/
class Menu extends TMenu
{ }
However each one of the two classes have a property to make a manytomany association between them (As mappedSuperclass doesn't allow an inverse side, my association is manytomany unidirectional).
I need to make a query inside MYBUNDLE. A query which join both tables with the manytomany association.
The reason i want to make this query inside MYBUNDLE, is because this bundle has a service which draws the Menu deppending in the Group or Groups. This method should be facilitate from this bundle, so other bundles could use it and i dont have to implemment in every sub-bundle.
My partial solution was to make a config part for my MYBUNDLE, something like:
mybundle:
menu_entity:
name: MyprojectChildBundle\Entity\Menu
group_entity:
name: MyprojectChildBundle\Entity\Group
With this configuration, I can use the repository of the child bundle inside MYBUNDLE, with this:
$this->em->getRepository("MyprojectChildBundle:Group")-findAll();
Everything works when I make a query without joins. On the other hand, when I do this:
$repo = $this->em->getRepository("MyprojectChildBundle:Group");
$result = $repo->createQueryBuilder("c")
->select('c, d')
->join("c.menus", "d")->getQuery()->getResult();
return $result
Everything fails, because the SQL formed try to look for a table called "Menu" which does not exist because it is called "sf_menu". The table Group is correctly changed to "sf_group" because I am using the Repository of my child. However using this repository just change the name of that class, but not of joined tables.
How could I make this kind of query inside MYBUNDLE? Thanks a lot.
Finally i found the solution :)
I had to create 2 more classes as my model. This classes should have all mapping Database and shoud be declared as single inheritance like this:
#src\Myproject\MYBUNDLE\Model\Menu
/**
* #ORM\Entity
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({"menu1" = "Myproject\MYBUNDLE\Entity\Menu", "menu2" = "Menu"})
*/
abstract class Menu {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// Other fields
}
That you should do with both entities (Menu and Group). The advantage of this implementation is that you don't lose any associations as before, due to declare them as mappedSuperClasss.
Then you should declare one entity per each model class and declare them as MappedSuperClass. They should look like this:
#src\Myproject\MYBUNDLE\Entity\Menu
use Doctrine\ORM\Mapping as ORM;
use Tixpro\TMenuBundle\Model\Menu as BaseMenu;
/** #ORM\MappedSuperclass */
class Menu extends BaseMenu
{
}
With this implementation you make sure not to lose any association. In addition, any entity could extend from your entities class to add more fields and customize them. For instance:
#src\Project\ChildBundle\Entity\Menu
use Myproject\MYBUNDLE\Entity\Menu as TMenu;
/**
* #ORM\Entity
* #ORM\Table(name="sf_menu")
*/
class Menu extends TMenu{
//put your code here
}
Don't forget to configure the params in the config.yml to use MYBUNDLE.
mybundle:
menu_entity:
name: MyprojectChildBundle\Entity\Menu
group_entity:
name: MyprojectChildBundle\Entity\Group
if you dont do this, you couldn't know the repository inside MYBUNDLE and consequently you couldn't make joined queries into your MYBUNDLE.
Finally, after setting your params and making that implementation, you are able to use joined queries inside your MYBUNDLE, like this:
$repo = $this->em->getRepository("MyprojectChildBundle:Menu");
$result = $repo->createQueryBuilder("wa")
->select('wa, da')
->join("wa.roles", "da")
That's all.

Exception : Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL

I am not able to authenticate in symfony2 with the 'Employee' entity as it contains many mapping with other entities in my project. some of my mapping is as follows:
/**
* #var EmployeeDesignation
*
* #ORM\ManyToOne(targetEntity="EmployeeDesignation")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="employee_designation_id", referencedColumnName="id")
* })
*/
private $employeeDesignation;
/**
* #var EmployeeDesignation
*
* #ORM\ManyToOne(targetEntity="EmployeeType")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="employee_type_id", referencedColumnName="id")
* })
*/
private $employeeType;
Authentication works fine without any mapping. I have tried with 'Serialize()' and 'Unserialize()' methods in it like below:
class Employee implements AdvancedUserInterface, \Serializable {
/**
* serialize the username
* #return serialize
*/
public function serialize() {
return serialize($this->emailOfficial);
}
/**
* unserialize
* #param $data
*/
public function unserialize($data) {
$this->em = unserialize($data);
}
}
I am getting the following error after doing the above method:
You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.
I have tried this way so as to get rid of the previous error, which is as follows:
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL
So, can anybody please suggest a way to overcome from this problem?
I have encountered something similar, and after some research, I tried the same things as you did.
But at some point, I found out that by setting the __sleep method, every thing worked fine.
class User implements PlayerInterface
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
...
public function __sleep()
{
return array('id');
}
...
Make sure that the field which is defined as #ORM\Id is part of the returned array.
Make sure to drop the browser cookie, since it uses the session.
I don't know exactly why it causes this when setting up a new association (mine was a ManyToMany), but It probably originate from this place:
// see Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse()
...
$event->getRequest()
->getSession()
->set('_security_'.$this->contextKey, serialize($token));
...
Hope this could help someone.
Edit:
References:
http://forum.symfony-project.org/viewtopic.php?f=23&t=35764
http://translate.google.com/translate?hl=en&sl=es&u=http://jonsegador.com/2012/03/error-con-symfony2-you-cannot-refresh-a-user-from-the-entityuserprovider-that-does-not-contain-an-identifier/
For me only this worked:
class User implements UserInterface
to
class User implements UserInterface, \Serializable
and I needed to add following methods to User class:
public function serialize() {
return serialize($this->username);
}
public function unserialize($data) {
$this->username = unserialize($data);
}
There is another possibility to solve this issue. You have to make the visibility of all properties of the entities which are associated with your user to 'protected'
See: http://www.metod.si/symfony2-error-usernamepasswordtokenserialize-must-return-a-string-or-null/
You should put "protected" in every variable of your user class. At least for me that work :)

Design choices to remove if-is statements

Say i have a class hierarchy of domain objects with one base class and a couple of child classes, one level.
Let say I have a list of those objects (list of the base class) and I want to apply some logic to the classes that I feel don't really belong to the classes (eg. design/UI specific code).
What are my alternatives ?
If-is statement. Personally this one shouldn't even be considered as an alternative but i write it anyway.
Polymorphism. This one is actually an alternative in some cases but with my example above, I don't want my classes to contain any UI specifics.
Resolving some logic method via reflection/IoC container based on the type of the object.
Eg C#. Type type = typeof(ILogic<>).MakeGenericType(domainObject.GetType());
I really like this one, I don't get any compile time checks though if an implementation is missing for a sub class, or is that possible somehow?
Visitor pattern. Will work but seemes kind of overkill to apply on a structure thats only one level deep.
Anyone has any other tips or tricks to solve these kinds of problems?
Great question. Problem is that there are many solutions and most of them will work.
I work with MVC a lot, similar situation happens quite often. Especially in the view, when similar rendering needs to happen across some views... but does not really belong to the view.
Let's say we have child class ChildList that extends BaseList.
Add a property uiHandler in the child class. Overload the rendering function, let's say toString(), and use the uiHandler with your specific UI/Design things.
I wrote a little something, it is in PHP... but you should be able to get an idea. It gives you freedom to chose how your objects will be displayed and flexibility to use specific UIs for specific objects.
Look at the code below, it seems like a lot but int's not that bad.
BaseList - your base class
BaseListUIExtended - base class that uses UI, takes optional UI class as constructor parameter. In C# 4 you can use optional, otherwise use 2 constructors.
UIBase - interface for UI classes...
UIChildSpecific - UI class
ChildList - child class that can use UI or not, because of BaseListUIExtended optional constructor parameter.
Define interface
/**
* Base UI interface
*/
interface IUIBase {
/**
* Renders the Base Class
*
* #param UIBase $obj
* #return string
*/
public function render($obj);
}
Define base classes, child class
//**************************************************************
// Define Base Classes
//**************************************************************
/**
* Base Class
*/
class BaseList {
/**
* List of items
* #var array
*/
protected $_items = array();
/**
* Gets collection of items
*
* #return array
*/
public function getItems() {
return $this->_items;
}
/**
* Adds new item to the list
* #param object $item
*/
public function add($item) {
$this->_items[] = $item;
}
/**
* Displays object
*/
public function display() {
echo $this->toString();
}
/**
* To String
*/
public function __toString() {
// Will output list of elements separated by space
echo implode(' ', $this->_items);
}
}
/**
* Extended BaseList, has UI handler
* This way your base class stays the same. And you
* can chose how you create your childer, with UI or without
*/
class BaseListUIExtended extends BaseList {
/**
* UI Handler
* #var UIBase
*/
protected $_uiHandler;
/**
* Default Constructor
*
* #param UIBase Optional UI parameter
*/
public function __construct($ui = null) {
// Set the UI Handler
$this->_uiHandler = $ui;
}
/**
* Display object
*/
public function display() {
if ($this->_uiHandler) {
// Render with UI Render
$this->_uiHandler->render($this);
} else {
// Executes default BaseList display() method
// in C# you'll have base:display()
parent::display();
}
}
}
//**************************************************************
// Define UI Classe
//**************************************************************
/**
* Child Specific UI
*/
class UIChildSpecific implements UIBase {
/**
* Overload Render method
*
* Outputs the following
* <strong>Elem 1</strong><br/>
* <strong>Elem 2</strong><br/>
* <strong>Elem 3</strong><br/>
*
* #param ChildList $obj
* #return string
*/
public function render($obj) {
// Output array for data
$renderedOutput = array();
// Scan through all items in the list
foreach ($obj->getItems() as $text) {
// render item
$text = "<strong>" . strtoupper(trim($text)) . "</strong>";
// Add it to output array
$renderedOutput[] = $text;
}
// Convert array to string. With elements separated by <br />
return implode('<br />', $renderedOutput);
}
}
//**************************************************************
// Defining Children classes
//**************************************************************
/**
* Child Class
*/
class ChildList extends BaseListUIExtended {
// Implement's logic
}
Testing...
//**************************************************************
// TESTING
//**************************************************************
// Test # 1
$plainChild = new ChildList();
$plainChild->add("hairy");
$plainChild->add("girl");
// Display the object, will use BaseList::display() method
$plainChild->display();
// Output: hairy girl
// Test # 2
$uiChild = new ChildList(new UIChildSpecific());
$uiChild->add("hairy");
$uiChild->add("girl");
// Display the object, will use BaseListUIExtended::display() method
$uiChild->display();
// Output: <strong>hairy</strong><br /><strong>girl</strong>