1

私のコード.................................:

<?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';
    }
}

init 関数が機能しないのはなぜですか? 多分私はいくつかの設定を変更する必要がありますか?または、標準の php __construct() を使用する必要がありますか?

4

3 に答える 3

3

ZF2 は安全にコンストラクターを使用できる__construct()ため、古い init()メソッドは削除されました。

http://www.mwop.net/blog/2012-07-30-the-new-init.html

于 2013-03-29T08:05:47.847 に答える
1

これはZF2で変更されました。同じことを実現したい場合は、コントローラーのコンストラクター (__construct()) で行うか、多くの凝った処理を行う必要がある場合は、コントローラーの Factory を作成し、モジュール構成で定義する必要があります。

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

TestControllerFactory は Zend\ServiceManager\FactoryInterface を実装する必要があります。つまり、createService メソッドを実装する必要があります。

于 2013-03-29T08:06:05.290 に答える
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
}

組み込みのイニシャライザが最初に呼び出されるため、スタックの一番下にイニシャライザを追加することをお勧めしServiceLocatorます。EventManagerinit()

于 2013-03-30T13:00:01.377 に答える