Get Boot­strap Resource every­where across your Zend_Application

Some­times you need to access some resources cre­ated inside your boot­strap some­where deep inside your applic­a­tion. There are two ways to achieve this. First is to use Zend_Registry, and second is to use resources of your boot­strap dir­ectly. Before we’ll fol­low, please ask your self: “Am I really need this?”, because in most cases you don’t need it, so this is a use­less post.

So, seems like you really need this use­less tip ;)) as you still here, so let’s start. The most known way to achieve this as I told before is Zend_Registry. So for example you can put some­thing like this into your init/bootstrap:

//somewhere in your bootstrap
Zend_Registry::set('myResourceName', $resource);

Then, you can access this $resource any­where as simple as:

// somewhere outside your bootstrap
$resource = Zend_Registry::isRegistered('myResourceName')
          ? Zend_Registry::get('myResourceName') : null;

Note that I used Zend_Registry::isRegistered() method to check if spe­cified key exists in the registry at all. Of course if you need to access more than one value, you bet­ter use instance of registry to min­im­ize some redund­ant calls:

$registry   = Zend_Registry::getInstance();
$resource_1 = $registry->offsetExists('myResource1')
            ? $registry->offsetGet('myResource1') : null;
$resource_2 = $registry->offsetExists('myResource2')
            ? $registry->offsetGet('myResource2') : null;

It was robust and simple. But if you use Zend_Application, then you would like to get access to your Boost­strap resources. For those who are not famil­iar with Boot­strap resources, I would like to make short intro­duce. There are two types of resources: first is sub­classes of Zend_Application_Resource_ResourceAbstract and second are meth­ods with _init pre­fix of your Boot­strap class. One very import­ant notice, when your resource returns a value, it will run only once, e.g.:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initFoo()
    {
        $t = microtime();
        echo 'Foo (' . $t . ')';
        return $t;
    }

    protected function _initBoo()
    {
        $t = microtime();
        echo 'Foo (' . $t . ')';
    }
}

Accord­ing to example above, $this->bootstrap('Foo'); will echo a string only once and you’ll be able to get $t value, by $this->getResource('Foo') in your Bootstrap class. But as _initBoo() doesn’t return any value it will be called every time (and in this dummy sample will echo string as many times as) $this->bootstrap('Boo') is called.

Let’s assume we have some resource described in our Boot­strap. For example, we want to have access to child val­ues of app from our applic­a­tion configuration:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initConfig()
    {
        return new Zend_Config((array) $this->getOption('app'));
    }
}

Also let’s say that our application.ini has at least fol­low­ing settings:

[production]
#...
app.name        = "My Application"
app.admin.email = "ixti@example.com"
app.admin.name  = "Aleksey V. Zapparov AKA ixti"
#...

First, for vivid pur­pose, here’s an example how this resource will work inside Bootstrap:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    // ...
    protected function _initLog()
    {
        // make sure Config resource is initiated first
        $cfg = $this->bootstrap('Config')->getResource('Config');

        $mail = new Zend_Mail();
        $mail ->addTo($cfg->admin->email, $cfg->admin->name);

        $writer = new Zend_Log_Writer_Mail($mail);
        $writer ->setSubjectPrependText('Errors with ' . $cfg->name);

        // Limit log event level for the writer
        $writer ->addFilter(Zend_Log::WARN);

        $log = new Zend_Log();
        $log ->addWriter($writer);

        return $log;
    }
}

Now, you want to get Con­fig resource some­where out­side your Boot­strap class. To do this you simply need to get an access to your Bootrstap instance, so you’ll be able to get any resource of it with some­thing like:

$admin = $bootrap->getResource('Config')->admin;

Of course if you have an access to your Zend_Application instance it’s not a big deal, as applic­a­tion have an appro­pri­ate method getBootstrap(), so you can get your boot­strap by:

$bootstrap = $application->getBootstrap();

But you don’t have a dir­ect access to applic­a­tion within ActionController. For­tu­nately, FrontController resource sets Boostrtrapboot­strap para­meter. So you can access both boot­strap and applic­a­tion from your Con­toller, without any addi­tional “dances”:

public class FooController extends Zend_Controller_Action
{
    public function init()
    {
        $front       = $this->getFrontController();
        $bootstrap   = $front->getParam('bootstrap');
        $application = $bootstrap->getApplication();
    }
}
  • del.icio.us
  • Google Bookmarks
  • Identi.ca
  • Twitter
  • Technorati
  • Digg
  • Slashdot
  • Facebook
  • MisterWong
  • Reddit
  • StumbleUpon
  • Mixx
  • HelloTxt
  • LinkedIn
  • PDF
  • email
  • Print
This entry was posted in Zend Framework and tagged , , . Bookmark the permalink.

One Response to Get Boot­strap Resource every­where across your Zend_Application

  1. Pingback: A Simple Resource Injector for ZF Action Controllers – Matthew … | PHP WebDev Insider

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>