Settings File tutorial
From PRADO Wiki
Contents |
Introduction
This tutorial will explain how to use a settings file to store settings for your applications. It's basically an .ini file that holds key/value pairs that you can access in your code. It should not be confused with application.xml that holds application logic etc. Our settings file will store information like WSDL locations, company name, logo urls, locale info etc. You can think of it like a site config.
To achieve this we need a setting file and a custom TApplication class.
Lets start by creating the settings file.
The settings file
The settings file will hold our settings. It's really up to you how you want to order the keys. I've found that using dots to group keys for the same service, and prefix the key groups with [servicename] is a nice way to keep things tidy. The rules for creating the ini file is pretty much tied up to the ini format.
I've created a mock up setting file.
myapp.ini source
[general] company.name = MyCompany company.logo = images/logo.jpg [site] site.url = http://www.mysite.com site.owner = webmaster@mysite.com [eservice] eservice.wsdl = https://www.myothersite.com/webservice&WSDL eservice.default_login = anon eservice.default_passwd = nopass
Custom application class
We need a custom application class to set up loading of the config file and access to the keys / values. This is pretty straight forward stuff. The constructor is overloaded to parse the ini file using parse_ini_file. It stores it in a private member called $config. We have getConfig which returns either a value based on a optional key or just the whole config if no key is supplied. If an invalid key is supplied an exception is thrown.
MyApplication.php source
<?php class MyApplication extends TApplication { protected $config; public function __construct($basePath = 'protected', $cacheConfig = true) { parent::__construct($basePath, $cacheConfig); $this->config = parse_ini_file('../conf/myapp.ini'); } public function getConfig($key = null) { if($key !== null) { if(isset($this->config[$key])) { return $this->config[$key]; } else { throw new Exception("Unknown key '$key' in configuration"); } } else { return $this->config; } } public function setConfig($config) { $this->config = $config; } } ?>
Usage
Since we've extended TApplication with our own MyApplication class we can access the config from anywhere as soon as MyApplication is constructed (remember to change the class in index.php where you create your application object.
The usage is as follows:
usage code
Inside MyApplication
$value = $this->config['key']
Elsewhere in code:
$value = $this->Application->config['key']; //or better $value = $this->Application->getConfig['key'];

