Search code examples
phpzend-framework

Accessing a controller action through out the application in Zend


I'm little bit new to Zend, I want to use a controller action through out the entire application automatically, I don't have a clear idea to how to use it, thought about init() method, action helpers, etc.


Solution

  • Then instead of simply creating controller action create controllerAction Helper . Here you can find more about it

    http://framework.zend.com/manual/en/zend.controller.actionhelpers.html

    My_Helper_Magic extends Zend_Controller_Action_Helper_Abstract
    {
    
    public function preDispach()
    {
         //code inside here will run for entire application automatically
    }
    
    }
    

    In your bootstrap do

    Zend_Controller_Action_HelperBroker::addHelper(new My_Helper_Magic());
    

    In Response to comment .

    It depends upon your 'code fragment' , If your code fragment does not required to know nothing about module , controller, action , base url then you can use Bootstrap init function

    like

    public function _initAlways()
    {
    //see how this function name is prefixed with _init hence it will be called by ZF //everytime. You can put your code fragment here 
    //If your code fragment depends upon some stuff like baseurl then do action controller
    // registration here instead 
     Zend_Controller_Action_HelperBroker::addHelper(new My_Helper_Magic());
    
    }
    

    In Response To comment

    You can save any instance of your object inside Zend_Registy and retrieve it whereever you like

    Inside Bootstrap.php

    public function _initSetup()
    {
    $object = new My_Custom_Object();
    Zend_Registry::set('my_custom_object',$object);
    }
    

    Later in your view or controller do

    $myObject = Zend_Registry::get('my_custom_object');  //to access it