Skip to content

Improve controller generation in make:crud command #788

Closed
@garak

Description

@garak

Description

Currently, the make:crud maker command generates actions that rely on explicit calls to Doctrine's manager.
I know that is already possible for user to change that code and improve it, but my point is about giving good suggestions (and I think current implementation fails on that).
Example of a generated code:

// in "new" action
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($tinyChef);
$entityManager->flush();
// in "edit" action
$this->getDoctrine()->getManager()->flush();
// in "delete" action
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($tinyChef);
$entityManager->flush();

This is breaking the law of Demeter, making controllers know too much about Doctrine internals.

My proposal is to add two methods to generated repository class: add and remove. The first method would be responsible to add/edit entity and the second one to delete it. With such methods (of course, by injecting repository in "new"/"edit"/"delete" actions), previous lines can be replaced with:

// in "new" action
$tinyChefRepository->add($tinyChef);
// in "edit" action
$tinyChefRepository->add($tinyChef);
// in "delete" action
$tinyChefRepository->remove($tinyChef);

This is an example of generated code for add method in repository class:

public function add(TinyChef $tinyChef, bool $flush = true): void
{
    $this->getEntityManager()->persist($tinyChef);
    if ($flush) {    // I think it's good to keep the opportunity to avoid flushing
        $this->getEntityManager()->flush();
    }
}

The remove method would be pretty the same (with remove instead of persist).

With such change, controllers wouldn't even know that they're handling Doctrine (except for namespaces), they would just rely on repositories.
I guess that, in a future, this could be also leading to deprecation/removal of getDoctrine() helper in the ControllerTrait.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions