2013-03-29 24 views
1

我的代碼...................:ZendFramework功能的init()不工作

<?php 
namespace Application\Controller; 

use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel; 

class IndexController extends AbstractActionController 
{ 

    public function init() 
    { 
     echo 'init worked'; 
    } 

    public function indexAction() 
    { 
     return new ViewModel(); 
    } 

    public function testAction() 
    { 
     echo 'test'; 
    } 
} 

爲什麼初始化函數不工作?也許我需要改變一些配置?或者我需要使用標準的php __construct()?

回答

1

這ZF2改變。如果你想完成同樣的事情,可以在你的控制器的構造函數中完成(__construct()),或者如果你需要做很多奇特的事情,你應該爲你的控制器創建一個Factory並在模塊配置中定義它。

'controllers' => array(
    'factories' => array(
      'TestController' => 'Your\Namespace\TestControllerFactory' 
    ) 
) 

的TestControllerFactory應實現的Zend \的ServiceManager \ FactoryInterface,這意味着它應該實現到createService方法。

+0

注意,工廠只需要爲controllersm注入依賴關係,而不需要'invokables'更簡單 – Maks3w

0

您可以添加自定義的初始化,使init()方法工作:

// in your Module class 
public function onBootstrap($e) 
{ 
    $cl = $e->getApplication()->getServiceManager()->get('ControllerLoader'); 

    $cl->addInitializer(function ($controller, $serviceManager) { 
     if (method_exists($controller, 'init')) { 
      $controller->init(); 
     } 
    }, false); // false means the initializer will be added in the bottom of the stack 
} 

添加初始化堆棧的底部是一件好事,因爲內置的初始化將被首先調用,所以你將有機會獲得到init()方法中的ServiceLocatorEventManager