2012-07-03 5 views
6

私は少し問題がある、私はコントローラがAbstractActionControllerを拡張し、任意のアクション、例えばindexActionの前にいくつかの関数を呼び出す必要がある私はpreDispatch()が何らかのアクションの前に呼び出すと思うが、 this-> view-> testは何もありません。preDispatchが動作しない

あなたはより良いモジュールクラスでこれを行うには、このようなMVCイベントハンドラにEventManagerを使用したい
class TaskController extends AbstractActionController 
{ 
private $view; 

public function preDispatch() 
{ 
    $this->view->test = "test"; 
} 

public function __construct() 
{ 
    $this->view = new ViewModel(); 
} 

public function indexAction() 
{ 
    return $this->view; 
} 
} 

答えて

7

class Module 
{ 
    public function onBootstrap($e) 
    { 
    $eventManager = $e->getApplication()->getEventManager(); 
    $eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 100); 
    } 

    public function preDispatch() 
    { 
    //do something 
    } 
} 
2

そして、1行で:

public function onBootstrap(Event $e) 
{ 
    $e->getTarget()->getEventManager()->attach('dispatch', array($this, 'someFunction'), 100); 
} 

最後の数字は体重です。マイナスの等しいポストイベントとして。

次のイベントが事前に設定されています:

const EVENT_BOOTSTRAP  = 'bootstrap'; 
const EVENT_DISPATCH  = 'dispatch'; 
const EVENT_DISPATCH_ERROR = 'dispatch.error'; 
const EVENT_FINISH   = 'finish'; 
const EVENT_RENDER   = 'render'; 
const EVENT_ROUTE   = 'route'; 
13

私はこれを行うことを望む場合は、私が定義されてonDispatchメソッドを使用します。詳細についてはhttp://mwop.net/blog/2012-07-30-the-new-init.htmlを見て、また

class TaskController extends AbstractActionController 
{ 
    private $view; 

    public function onDispatch(\Zend\Mvc\MvcEvent $e) 
    { 
    $this->view->test = "test"; 

    return parent::onDispatch($e); 
    } 

    public function __construct() 
    { 
    $this->view = new ViewModel(); 
    } 

    public function indexAction() 
    { 
    return $this->view; 
    } 
} 

をZF2でのディスパッチイベントの操作方法について

+1

私はGoogleでこれを発見しました。私はディスパッチで親に電話することを忘れました... – Ismael

関連する問題