How can I access the configuration of a Zend Framework application from a controller?

Viewed 48295

I have a Zend Framework application based on the quick-start setup.

I've gotten the demos working and am now at the point of instantiating a new model class to do some real work. In my controller I want to pass a configuration parameter (specified in the application.ini) to my model constructor, something like this:

class My_UserController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $options = $this->getFrontController()->getParam('bootstrap')->getApplication()->getOptions();
        $manager = new My_Model_Manager($options['my']);
        $this->view->items = $manager->getItems();
    }
}

The example above does allow access to the options, but seems extremely round-about. Is there a better way to access the configuration?

7 Answers

Since version 1.8 you can use the below code in your Controller:

$my = $this->getInvokeArg('bootstrap')->getOption('my');

I've define a short hand in some place I require_once() in the beginning of boostrap:

function reg($name, $value=null) {
    (null===$value) || Zend_Registry::set($name, $value);
    return Zend_Registry::get($name);
}

and in the bootstrap I have a:

protected function _initFinal()
{
    reg('::app', $this->getApplication());
}

then I can get the Application instance anywhere by use:

$app = reg('::app');

A really simple way to access the configuration options is by directly accessing the globally defined $application variable.

class My_UserController extends Zend_Controller_Action {
    public function indexAction() {
        global $application;
        $options = $application->getOptions();
    }
}
Related