2009年4月1日星期三

[fw-mvc] Reusing controller instances

I have a simple controller set up that contains two actions. When I call $this->action from within a view script on the other action in the same controller, it seems that a new instance of the controller is created instead of reusing it. This means that my init() method is being called twice. Is there a way to prevent the dispatcher from creating new instances of the same controller during the same request? Can it be made to re-use an existing controller object and only call preDispatch(), action, postDispatch()?

Here's some simple test code showing init() being called twice.

<?php

class MyTestController extends Zend_Controller_Action
{
    public function init()
    {
        parent::init();
        echo 'MyTest controller initialized<br />';
    }

    public function preDispatch()
    {
        // disable view script rendering for all actions
        $this->_helper->viewRenderer->setNoRender(true);
        // disable layout for testing
        $this->_helper->layout->disableLayout(true);
    }

    public function indexAction()
    {
        echo 'index action called<br />';
        // also render search action
        echo $this->view->action('search', 'my-test', 'default', array());
    }

    public function searchAction()
    {
        echo 'search action called<br />';
    }
}

Output:
MyTest controller initialized
index action called
MyTest controller initialized
search action called

-Hector

没有评论: