I am working with Symfony2 and Doctrine ORM and want to achieve the following with a clean architecture :
Each time a new Entity is created, I want to save a "display name" chosen by my end-user, then generate a "unique name" based on the "display name".
If my end-user want to create 3 Project called "Drawings",
- the first one will have display_name = "drawings"
- the second one will have display_name = "drawings2"
- the third one will have display_name = "drawings3"
(or something like that, whatever the pattern)
Basic Entity example :
/**
* Project.
*
* @ORM\Entity
*/
class Project
{
//...
/**
* @ORM\Column(type="string", length=50, nullable=false)
*/
protected $name_display ;
/**
* @ORM\Column(type="string", length=50, nullable=false, unique=true)
*/
protected $name_unique ;
//...
Basic usage example :
$project = new Project();
$project->setDisplayName('Drawings');
//Around here I would like the Unique name to be generated
$this->getDoctrine()->getManager()->persist($project);
I thought about various solutions :
- Doing the name generation in the Controller, but it's not re-usable
- Doing the unique name generation in the repository. But it seem to be a bad practive (repositories should be read-only)
- Using a PrePersist LifecycleCallbacks from doctrine, but it's not a good practice as I need the Entity Manager to do a Database
- Doing the name generation in the Entity Setter, injecting the Entity Manager to make requests and look for available names. That looks horrible
- Using a service to persist the Entity as explained here : Are Doctrine2 repositories a good place to save my entities? (But it's quite complicated and involve a huge change in my infrastructure if I want to have all my Entity creations to be consistent with this practice)