2017-03-07 56 views
0

例如,下面的代码:作为服务的Symfony控制器如何与__invoke方法一起使用?

/** 
* @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, 
     ]); 
    } 
} 

为什么要为__invoke是空的路线标注? 这个控制器的生命周期是什么?我的意思是,Symfony何时创建对象,何时执行该类以利用__invoke

回答

0

空的@Route注释表示在主要路线/patients之后没有任何东西。 __invoke是一个神奇的PHP方法,当你将你的类作为一个函数调用时(不提供任何方法),它会被执行。 因此,当您点击路线/patients或从任何代码调用服务时,都会执行__invoke方法。

相关问题