2

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)
Community
  • 1
  • 1
Wink
  • 43
  • 6

1 Answers1

2

I would recommend the last options - services. It may need changes in your project, but I find this the best way to manage usual crud operations with entities - create, save, findBySomething ...

  • It is crystal clear - no black magic. As opposed to events where there is no obvious relation between the executed code and actions with entities (like creating it through new).
  • It is not dependent on annotations and it is easy to maintain.
  • Controllers and other services may access this service through Dependency Injection which is a clear way of satisfying dependencies of business objects(objects holding business logic)
  • Your repositories won't become bigger and bigger
  • You can use default repositories - fewer issues with back compatibility when upgrading Doctrine
  • It is much better than the "setter solution", which sounds really horrible - entities should never be that mighty, so they would have references to services (especially services like EntityManager)
Jan Mares
  • 795
  • 10
  • 22