Symfony 控制器即服务如何与 __invoke 方法一起工作?

Jor*_*eFG 2 service symfony

例如,在以下代码中:

/**
 * @Route("/patients", service="bundle1.controller.patient.index")
 */
final class IndexController
{
    private $router;
    private $formFactory;
    private $templating;
    private $patientFinder;

    public function __construct(RouterInterface $router, FormFactoryInterface $formFactory, EngineInterface $templating, PatientFinder $patientFinder)
    {
        $this->router = $router;
        $this->formFactory = $formFactory;
        $this->templating = $templating;
        $this->patientFinder = $patientFinder;
    }

    /**
     * @Route("", name="patients_index")
     */
    public function __invoke(Request $request) : Response
    {
        $form = $this->formFactory->create(PatientFilterType::class, null, [
            'action' => $this->router->generate('patients_index'),
            'method' => Request::METHOD_GET,
        ]);
        $form->handleRequest($request);
        $patients = $this->patientFinder->matching($form->getData() ?: []);

        return $this->templating->renderResponse('patient/index.html.twig', [
            'form' => $form->createView(),
            'patients' => $patients,
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么路径注释是__invoke空的?该控制器的生命周期是多少?我的意思是,Symfony 何时创建对象以及何时执行要使用的类__invoke

mal*_*olm 6

@Route注释意味着类的主路径之后没有任何内容/patients__invoke是一个神奇的 PHP 方法,当您将类作为函数调用时(不提供任何方法),就会执行该方法。因此,__invoke当您点击路线/patients或从任何代码调用服务时,都会执行该方法。