Symfony:为什么我的容器在我的控制器中为空?

Symfony : why my container is null in my controller?

使用 Symfony 3.3,我有一个控制器 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);
        }
    }
}

这个控制器调用其他控制器:TrainingCenterControllerdelete()函数:

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

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

但是我在 delete 函数上有这个错误:"Call to a member function get() on null"。我不明白,因为我的控制器作为服务,我有默认配置:

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

你能帮帮我吗?我想调用几个控制器进行级联删除(而不是重复代码):)

您正在将控制器用作通用服务 - 最好使用常规服务 - 您构造函数 - 在其中注入原则实例,并从需要的任何地方调用该服务 - 通过 ->get(name::class) 或使用具有完整 __constructor(TypeHint $serviceName).

的完整服务驱动控制器

当系统创建控制器并调用操作(或 __invoke() 它)时,发生的另一件事是 ContainerAwareTrait 允许 setContainer()调用 - 常规服务不会发生这种情况。