2017-03-07 19 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方法。

相關問題