2012-06-06 33 views

回答

23

在Symfony2中沒有預處理方法。您必須爲此使用event listeners

+3

該死的,好吧。謝謝;) – bux

+0

我需要補充的是,雖然本身沒有預處理方法,但事件'kernel.controller'可能是您想要的。 – PhoneixS

15

可能使用監聽器是實現「後控制器初始化任務」更優雅的方式,但有更簡單的方法來做到這一點:

use Symfony\Component\DependencyInjection\ContainerInterface; 

/** 
* Override method to call #containerInitialized method when container set. 
* {@inheritdoc} 
*/ 
public function setContainer(ContainerInterface $container = null) 
{ 
    parent::setContainer($container); 
    $this->containerInitialized(); 
} 

/** 
* Perform some operations after controller initialized and container set. 
*/ 
private function containerInitialized() 
{ 
    // some tasks to do... 
} 

將此代碼插入到控制器中,或者,如果您願意,甚至可以將其插入到控制器的某個基本父抽象中。

因爲容器會在每個控制器初始化時設置,我們可以覆蓋setContainer方法來執行一些容器設置後的任務。

+0

有趣!我會測試:) – bux

+0

這需要'使用Symfony \ Component \ DependencyInjection \ ContainerInterface;' – totas

+0

很好的答案。有用。我會選擇這種方式。 – Sithu

相關問題