Accessing ZF Application Resources In Controller

My friend Rob Allen recently posted a quick how-to on how to access your configuration data in application.ini file while in a controller or action helper. The one part Rob didn’t touch on was how to get resources back.

Resources are set when you return something out of your _init<MethodName>. For example when you use the following source code and return the $_logger, Zend_Application stores the returned value in a registry inside the application.

// place in your bootstrap file.
public function _initLogger()
{
    $writer = new Zend_Log_Writer_Firebug();
    $_logger = new Zend_Log($writer);
    return $_logger;
}

Now the way you get access to the logger is by doing the following inside your controller or controller helper:

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        // action body
        $logger = $this->getInvokeArg('bootstrap')
                        ->getResource('logger');
    }
}

The key is the getResource() method. You pass in the part following the _init from your method name. This will return the instance of what ever object was returned in the _init method.

Where I got stuck, was since I’m using the Module Bootstrap for my modules and I only want the logger on specific modules and not the whole application when I used the above code it returned null. The reason for null was because it was not in the global bootstrap file. To get access to the resources from the module bootstrap you need to use the following code:

class Admin_IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        // action body
        $logger = $this->getInvokeArg('bootstrap')
                        ->getResource('modules')
                        ->offsetGet($this->getRequest()->getModuleName())
                        ->getResource('logger');
    }
}

I hope this helps someone else out there as it was an eye opener to me when I was told about it via the ZF mailing list.

4 Comments

  1. Is there a way to access the logger from within a Plugin that is registered in the application

  2. Thanks, what I need for moduler bootstrap

Trackbacks/Pingbacks

  1. Zend Framework in Action » Accessing Zend_Application resources in a controller - [...] Whitcraft has posted an article explaining how to access Zend_Application resources from within a controller. He also points out ...
  2. PHP-help » Accessing Zend_Application resources in a controller - [...] Whitcraft has posted an article explaining how to access Zend_Application resources from within a controller. He also points out ...

Leave a Reply