Zend Framework: (3) Read Config Variable in Controller
My third post will be much smaller than the first and the second one. This is about a point i’ve searched for several times. It looks like there ain’t no better solution for that.
Zend Framework supports configuration ini-files. These files are usually saved in /application/configs/. The main file that is created by the quickstart is application.ini. You can add your own directives to this file and therefore have a solid, simple and easy to handle (but static) configuration.
To access this variables in your controller, just use the following lines:
$bootstrap = $this->getInvokeArg(‘bootstrap’);
$config = $bootstrap->getOptions();echo $config['myVariable'];
This is it. Quite simple, huh? I haven’t found a way (up to now) to get this in less lines, but there has to be.
There is also a way to access those configuration variables globally via Zend_Registry. Practically one would create an _init-function in the Bootstrap and use the getOptions()-function to get the config. Then you just add Zend_Registry::set(‘key’, ‘value’) to save the variable globally. To access it afterwards, call $value = Zend_Registry::get(‘key’) in any of your controller actions.
If you use an huge configuration file that hasn’t been loaded automatically, you’ll have to rely on the Zend_Config. This is overall a configuration file parser. An easy example is the following:
- Create an ini-file (“myconfig.ini”) in your application/config-directory. Insert any directives, e.g. myconf.var1.value = test.
- Read the configuration file with an Zend_Config_Ini-object: $myconfig = new Zend_Config_Ini(‘application/config/myconfig.ini’). If you used sections in your configuration file (like [production] and [development] in the application.ini), add a second parameter with the targeted section.
- Access the directives in the config file in an object-based way: echo $myconfig->myconf->var1->value; // this echoes “test”.
Config is very easy. You just have to get in touch with it for the first time. There are plenty of useful examples in the documentation (contrary to many other libraries).
I’m just getting started with Zend Framework, mostly using a few components here on existing projects that don’t yet employ the full MVC stack.
One of my tasks this very afternoon on one of these non-ZF apps is is to move my config data to an ini file, create an instance of Zend_Config with that ini file, and stash it away using Zend_Registry, just like you described.
Thanks!
Kommentar by David Weinraub — 3. Oktober 2009 @ 09:55
Thanks. The first way is good. Less lines? Only that
$config = $this->getInvokeArg(‘bootstrap’)->getOptions();
Kommentar by dV — 12. November 2009 @ 21:18