views:

313

answers:

3

I am trying to store my Google Maps API Key in my application.ini file, and I would like to be able to read it from my controller whenever its needed. How can I go about reading values from the application.ini from my controller?

Thanks!

+2  A: 

Either through the FrontController

// bootstrap
$front->setParam('GMapsApiKey', 123456);

// controller
$this->getFrontController()->getParam('GMapsApiKey');

or Registry:

// bootstrap
Zend_Registry::set('GMapsApiKey', '123456');

// controller
Zend_Registry::get('GMapsApiKey');

However, since access to the Google Maps API is something that happens in the model, your controller should not need to know the API key.

Gordon
Is there any way to just read it when I need it? I was trying to avoid doing it in the bootstrap on every request, as it will only be needed on a small fraction of pages
Ryan
@Ryan the bootstrap and application.ini will get called on every request anyway, so you gain nothing but maybe a microsecond by not doing it this way. If you'd load the application.ini on demand, you'd have an additional I/O request. That's much slower.
Gordon
Thanks Gordon, that makes a lot of sense. I am confused as to how this would go in the model though. I was planning on creating a provider (aka "model") for Google Maps, but ultimately I need it in the view in order to pass it along to Google via the JavaScript API request.
Ryan
@Ryan I haven't worked with any of the Google APIs or Zend_GData classes yet, but here is a screencast and example code: http://www.zendcasts.com/using-google-maps-with-zend_gdata/2009/09/ - maybe that helps. They define the keys in the controller though. If you just need the API key in the View, you can set it to the view when you init the view as well.
Gordon
+3  A: 

This article might help you out. The author explains how to retrieve gmail connection params from the application.ini file.

You might want to try:

$bootstrap = $this->getInvokeArg('bootstrap');
$aConfig = $bootstrap->getOptions();
googleMapsKey = $aConfig['your_resource']['your_key'];
Thomas
If you're in a front controller this is good solution. A full set of options is here: http://akrabat.com/zend-framework/accessing-your-configuration-data-in-application-ini/
Rob Allen
A: 

I tend to do this in the bootstrap, and then as Gordon mentions toss it in the registry. You can then get it anywhere out of the registry.

$this->config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
Zend_Registry::set('config', $this->config);

Also, to his point, the controller would tend to be the wrong place for it, unless you are accessing the API with multiple keys, I guess, but even then you should be able to place the logic in the model to select a key from the registry.

whoughton