Search code examples
symfonysymfony-3.3

Symfony : why my container is null in my controller?


With Symfony 3.3, I have a Controller TrainingOrganizationController :

class TrainingOrganizationController extends Controller
{
    @Route...
    public function deleteAction(Request $request, UserInterface $user, TrainingOrganization $organization)
    {
        ...
        $this->delete($user, $organization);
        ...
    }

    public function delete(UserInterface $user, TrainingOrganization $organization)
    {
        $organization->setDeletedAt(new \DateTime());
        $organization->setDeletedBy($user);

        $entityManager = $this->getDoctrine()->getManager();

        $centers = $entityManager->getRepository(TrainingCenter::class)->getResults([
            'whereTrainingOrganizationId' => $organization->getId(),
        ]);

        foreach ($centers as $center) {
            $this->get(TrainingCenterController::class)->delete($user, $center);
        }
    }
}

This Controller call other Controller : TrainingCenterController and delete() function :

class TrainingCenterController extends Controller
{
    public function delete(UserInterface $user, TrainingCenter $center)
    {
        $center->setDeletedAt(new \DateTime());
        $center->setDeletedBy($user);

        $entityManager = $this->getDoctrine()->getManager(); // ERROR
        ...

But I have this error on delete function : "Call to a member function get() on null". I don't understand because my controller as service, I have the default config :

AppBundle\Controller\:
    resource: '../../src/AppBundle/Controller'
    public: true
    tags: ['controller.service_arguments']

Can you help me ? I want to call several controllers for cascading deletes (and not to repeat the code) :)


Solution

  • You're using a controller as a generic service - better to use a regular service - into which you constructor-inject a doctrine instance, and call that service from wherever is required - via ->get(name::class) or with a full service-driven controller with full __constructor(TypeHint $serviceName).

    When the system creates a controller, and calls the action (or __invoke() it), one of the other things that happen is that the ContainerAwareTrait allows for setContainer() to be called - which does not happen for regular services.