Home » Configuration » Config » Manual
The Config package provides methods for configuration manipulation.
Introduction
Config helps you manipulate your configuration whether they are stored in XML files, PHP arrays or other kind of datasources. It supports these features:
- Parse different configuration formats.
- Manipulate sections, directives, comments, blanks the way you want.
- Write them back to a datasource in your preferred format.
The Config object acts as a container for other Config_Container objects. It doesn't do much but makes handling IO operations easier. It contains the root Config_Container object which in turn contains a child Config_Container object. Config_Container objects store references to their parent and have an array of children. This structure makes it easy to access the different containers and their contents.
A Config_Container object can be of different type:
- Section: a section contains other Config_Container objects.
- Directive: a directive does not contain any other object but has content and a name. See them as key-value pairs.
- Comment: just like directives, comments have content but they don't have a name. They are rendered in a special way according to the configuration type you choosed.
- Blank: they don't have neither content or name but are used to indicate blank lines if your renderer uses them.
When using the Config package, most of the work is done with Config_Container objects.
An example that will create a new Config_Container
<?php
// initialize a Config_Container object
require_once('Config.php');
$conf =& new Config_Container('section', 'conf');
$conf_DB =& $conf->createSection('DB');
$conf_DB->createDirective('type', 'mysql');
$conf_DB->createDirective('host', 'localhost');
$conf_DB->createDirective('user', 'root');
$conf_DB->createDirective('pass', 'root');
// set this container as our root container child in Config
$config = new Config();
$config->setRoot($conf);
// write the container to a php array
$config->writeConfig('/tmp/config_test.php', 'phparray',
array('name' => 'test'));
// print the content of our conf section to screen
echo $conf->toString('phparray', array('name' => 'test'));
?>
The above example illustrates how Config and Config_Container can interact. There are other ways. You could have for example first created the Config object and then used $config->getRoot() to add sections and directives to the returned object reference.
Reading configuration from an XML file
<?php
require_once 'Config.php';
$conf = new Config;
$root =& $conf->parseConfig('config.xml', 'XML');
if (PEAR::isError($root)) {
die('Error while reading configuration: ' . $root->getMessage());
}
$settings = $root->toArray();
printf('User settings: <a href="%s">%s %s</a>',
$settings['root']['conf']['www'],
$settings['root']['conf']['firstname'],
$settings['root']['conf']['lastname']
);
?>
In this example the XML file config.xml
looks like this:
<?xml version="1.0" encoding="UTF-8"?> <conf> <firstname>John</firstname> <lastname>Doe</lastname> <www>http://example.com/</www> </conf>
For more information, You can read API doc, sample of package, tests of package, and a great tutorial of DevShed about the Config package.
Editing a configuration
There are many ways to create content in your Config object. You can simply pass it an array like it is shown in the example below:
Create configuration with array
<?php
// configuration array
$conf = array(
'DB' => array(
'type' => 'mysql',
'host' => 'localhost',
'user' => 'root',
'pass' => 'root'
)
);
// Config object
$config = new Config();
$root =& $config->parseConfig($conf,
'phparray',
array('name' => 'conf'));
echo $root->toString('phparray', array('name' => 'conf'));
?>
You can also ask Config to look for a file on your filesystem and try to parse it. You would then do it like this. This example assumes you have a valid XML file:
Create configuration with a file
<?php
// Config object
$config = new Config();
$root =& $config->parseConfig('/path/to/file.xml', 'xml');
echo $root->toString('phparray', array('name' => 'conf'));
?>
At the moment, Config can parse XML, PHP arrays, ini files, Apache conf and other generic type of configurations with comments and key-value pairs.
Of course, it is also possible to create the configuration from scratch as shown in the previous section example.
Available Containers
Supported configuration file types
The Config package supports reading and writing to different "containers" - types of configuration files. Ini-style configuration files are very common.
| Container | Comments | Sections | Nested sections | Multiline strings | Boolean | Int/float | Null |
|---|---|---|---|---|---|---|---|
| Apache | yes | yes | yes | - | (yes)* | (yes)* | (yes)* |
| GenericConf | yes | - | - | yes | (yes)* | (yes)* | (yes)* |
| IniCommented | yes | yes | - | - | (yes)* | (yes)* | (yes)* |
| IniFile | - | yes | - | yes | (yes)* | (yes)* | (yes)* |
| PHPArray | - | yes | yes | yes | yes | yes | yes |
| PHPConstants | yes | - | - | - | (yes)* | (yes)* | (yes)* |
| XML | no | yes | yes | yes | (yes)* | (yes)* | (yes)* |
(yes)*indicates that saving and loading those types does work, but the type of the variable is "string" after reading the config file.
Apache
Parses and saves Apache configuration files. No options are provided by this container.
Writing an apache configuration file
This example script will create a new apache configuration file
for a virtual host. It first adds a
Listen directive
and then a virtual host section containing its settings.
<?php
require_once 'Config.php';
$conf = new Config();
$root = $conf->getRoot();
$root->createDirective('Listen', '82');
$root->createBlank();
$root->createComment('My virtual host');
$vhost = $root->createSection('VirtualHost', array('127.0.0.1:82'));
$vhost->createDirective('DocumentRoot', '/usr/share/www');
$vhost->createDirective('ServerName', 'my-pear.example.org');
$conf->writeConfig(sys_get_temp_dir() . '/dummy-apache.conf', 'apache');
?>
Generated configuration file
# My virtual host <VirtualHost 127.0.0.1:82> DocumentRoot /usr/share/www ServerName my-pear.example.org </VirtualHost>
Reading an existing config file
Our task is to open an existing Apache configuration file and
extract all Listen directives from it, using
the container's
getItem
method.
Config file
# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default
# This is also true if you have upgraded from before 2.2.9-3 (i.e. from
# Debian etch). See /usr/share/doc/apache2.2-common/NEWS.Debian.gz and
# README.Debian.gz
NameVirtualHost *:80
Listen 80
Listen 82
<IfModule mod_ssl.c>
# If you add NameVirtualHost *:443 here, you will also have to change
# the VirtualHost statement in /etc/apache2/sites-available/default-ssl
# to <VirtualHost *:443>
# Server Name Indication for SSL named virtual hosts is currently not
# supported by MSIE on Windows XP.
Listen 443
</IfModule>
<IfModule mod_gnutls.c>
Listen 443
</IfModule>
PHP script
<?php
require_once 'Config.php';
$file = dirname(__FILE__) . '/apache-read-config.txt';
$conf = new Config();
$root = $conf->parseConfig($file, 'apache');
if (PEAR::isError($root)) {
echo 'Error reading config: ' . $root->getMessage() . "\n";
exit(1);
}
$i = 0;
while ($item = $root->getItem('directive', 'Listen', null, null, $i++)) {
echo $item->name . ': ' . $item->content . "\n";
}
?>
GenericConf
Generic configuration files. The equals, comment start and new line characters in the parser can be customised to match your preferred configuration format.
| Option | Data Type | Default value | Description |
|---|---|---|---|
comment |
string | # |
The character that signifies the start of a comment. |
equals |
string | : |
The character that separates keys from values. |
newline |
string | \ |
The character that signifies that a value continues across multiple lines. |
Writing a config file with custom options
<?php
require_once 'Config.php';
$conf = new Config();
$root = $conf->getRoot();
$root->createComment('Demo config file with GenericConf container');
$root->createDirective('openLastFile', true);
$root->createBlank();
//GenericConf does not support sections, but section contents are serialized
// into the main config namespace
$dbsect = $root->createSection('database');
$dbsect->createDirective('host', 'db-server.example.org');
$dbsect->createDirective('name', 'demo-db');
$r = $conf->writeConfig(
'generic-conf-write.txt',
'genericconf',
array(
'comment' => '#',
'equals' => '=>',
)
);
if (PEAR::isError($r)) {
echo $r->getMessage() . "\n";
}
?>
Generated file
#Demo config file with GenericConf container openLastFile=>1 host=>db-server.example.org name=>demo-db
IniCommented
Parses standard INI files, maintaining comments within the file.
In contrast to
IniFile,
the IniCommented container parses the ini file manually using
regular expressions and is slower.
If you only read the file, using IniFile is more appropriate since it's faster.
| Option | Data Type | Default value | Description |
|---|---|---|---|
linebreak |
string | \n |
Character(s) used to separate lines from each other. |
Writing a .desktop file
<?php
require_once 'Config.php';
$conf = new Config();
$root = $conf->getRoot();
//note: inicommented uses ";" as comment indicator while the desktop entry spec
// says that it has to be "#" - so no comments for .desktop files
$entry = $root->createSection('Desktop Entry');
$entry->createDirective('Version', '1.0');
$entry->createDirective('Type', 'Link');
$entry->createDirective('URL', 'http://pear.php.net/');
$entry->createDirective('Name', 'go to pear.php.net');
$entry->createDirective('Icon', 'gnome-fs-bookmark');
$r = $conf->writeConfig(
'/home/cweiske/Desktop/pear.php.net.desktop',
'inicommented',
//windows newlines are not required in desktop files;
// they just serve as example how to use container options
array('linebreak' => "\r\n")
);
if (PEAR::isError($r)) {
echo $r->getMessage() . "\n";
}
?>
Generated file
[Desktop Entry] Version = 1.0 Type = Link URL = http://pear.php.net/ Name = go to pear.php.net Icon = gnome-fs-bookmark
IniFile
Parse standard INI files using PHP's in built parse_ini_file(). Does not read in comments. No options are available for this container.
Reading a .ini file
Ini file
[database] host=db.example.org user=bloguser pass=blogpassword
<?php
require_once 'Config.php';
$file = dirname(__FILE__) . '/ini-file-read.txt';
$conf = new Config();
$root = $conf->parseConfig($file, 'inifile');
if (PEAR::isError($root)) {
echo 'Error reading config: ' . $root->getMessage() . "\n";
exit(1);
}
$cfg = $root->toArray();
echo "Database connection:\n";
echo ' Host: ' . $cfg['root']['database']['host'] . "\n";
echo ' User: ' . $cfg['root']['database']['user'] . "\n";
echo ' Password: ' . $cfg['root']['database']['pass'] . "\n";
?>
Output
Database connection:
Host: db.example.org
User: bloguser
Password: blogpassword
PHPArray
Parses PHP Array structures. Can read from a PHP Source file or from an in memory array. Due to technical limitations, this container does not parse blank lines or comments when reading from a configuration file, therefore any information contained within PHP comments will be lost.
| Option | Data Type | Default value | Description |
|---|---|---|---|
name |
string | conf |
The name to use for the root configuration variable, both when parsing and writing PHP source files. |
useAttr |
boolean | TRUE | Controls whether attributes are parsed and saved. |
Since config files containing php arrays are just included using the standard php methods, code comments and structure will be lost when saving.
Writing a PHPArray config file
<?php
require_once 'Config.php';
$conf = new Config();
$root = $conf->getRoot();
$root->createComment('Demo config file with PHPArray container');
$root->createDirective('openLastFile', true);
$root->createBlank();
$dbsect = $root->createSection('database');
$dbsect->createDirective('host', 'db-server.example.org');
$dbsect->createDirective('name', 'demo-db');
//this is a nested section
$subsect = $dbsect->createSection('settings');
$subsect->createDirective('charset', 'utf-8');
$subsect->createDirective('reconnect', true);
$r = $conf->writeConfig('php-array-write.txt', 'phparray');
if (PEAR::isError($r)) {
echo $r->getMessage() . "\n";
}
?>
Generated file
<?php
// Demo config file with PHPArray container
$conf['openLastFile'] = true;
$conf['database']['host'] = 'db-server.example.org';
$conf['database']['name'] = 'demo-db';
$conf['database']['settings']['charset'] = 'utf-8';
$conf['database']['settings']['reconnect'] = true;
?>
PHPConstants
Parses a set of PHP define() from a PHP source file. Comments are maintained by this container, although blank lines will be lost. There are no options for this container.
Writing a PHPConstants config file
<?php
require_once 'Config.php';
$conf = new Config();
$root = $conf->getRoot();
$root->createComment('Demo config file with PHPConstants container');
$root->createDirective('openLastFile', true);
$root->createBlank();
//PHPConstants container does not support sections but puts them in the main
// namespace
$dbsect = $root->createSection('database');
$dbsect->createDirective('host', 'db-server.example.org');
$dbsect->createDirective('name', 'demo-db');
$r = $conf->writeConfig('php-constants-write.txt', 'phpconstants');
if (PEAR::isError($r)) {
echo $r->getMessage() . "\n";
}
?>
Generated file
<?php
/**
*
* AUTOMATICALLY GENERATED CODE - DO NOT EDIT BY HAND
*
**/
// Demo config file with PHPArray container
define('OPENLASTFILE', true);
//
// database
//
define('HOST', 'db-server.example.org');
define('NAME', 'demo-db');
?>
XML
Parses a XML file using XML_Parser.
| Option | Data Type | Default value | Description |
|---|---|---|---|
version |
string | 1.0 |
The XML version to use. |
encoding |
string | ISO-8859-1 |
The content encoding to use when parsing and storing data. |
name |
string | conf |
As with PHPArray, this defines the name of the global configuration root. |
indent |
string | |
The character used for indentation when writing the XML document, if any. By default, two spaces are used. |
linebreak |
string | \n |
The line-breaking character(s) to use when writing the XML document. |
addDecl |
boolean | TRUE | Controls whether the XML declaration is added to the start of the XML document. |
useAttr |
boolean | TRUE | Controls whether attributes are parsed and saved. |
isFile |
boolean | TRUE | If TRUE, the first argument to parseConfig() will be taken as the file name for the XML file to load. If FALSE, the argument will be taken as the XML data itself and parsed accordingly. |
useCData |
boolean | FALSE | Controls whether data is enclosed in CDATA blocks. |
To utilize the XML container, you need to have the XML_Parser package installed (optional dependency).
Writing a config file with the XML container
<?php
require_once 'Config.php';
$conf = new Config();
$root = $conf->getRoot();
$root->createComment('Demo config file with XML container');
//we need a main section, otherwise we get invalid XML
// see http://pear.php.net/bugs/bug.php?id=18357
$main = $root->createSection('config');
$main->createDirective('openLastFile', true);
$main->createDirective('rememberFiles', 8);
$main->createBlank();
$dbsect = $main->createSection('database');
$dbsect->createDirective('host', 'db-server.example.org');
$dbsect->createDirective('name', 'demo-db');
//this is a nested section
$subsect = $dbsect->createSection('settings');
$subsect->createDirective('charset', 'utf-8');
$subsect->createDirective('reconnect', false);
$r = $conf->writeConfig(
'xml-write.txt',
'xml',
array(
'encoding' => 'UTF-8',
'indent' => ' ',
)
);
if (PEAR::isError($r)) {
echo $r->getMessage() . "\n";
}
?>
Generated file
<?xml version="1.0" encoding="UTF-8"?> <!-- Demo config file with XML container --> <config> <openLastFile>1</openLastFile> <rememberFiles>8</rememberFiles> <database> <host>db-server.example.org</host> <name>demo-db</name> <settings> <charset>utf-8</charset> <reconnect /> </settings> </database> </config>
Config class
Config::Config
Config::Config() – constructor
Synopsis
require_once 'Config.php';
object Config::Config (
void
)
Description
The Config constructor, it creates a config object.
The next thing you should do is getting the root Config_Container object with getRoot() .
Config::getRoot
Config::getRoot() – Return root container for config object
Synopsis
require_once 'Config.php';
object &Config::getRoot (
void
)
Description
This method returns a reference to the root Config_Container object in the Config object. Use the returned Config_Container object reference to manipulate your configuration data.
Return value
object -
a reference to config's root container object
Note
This function can not be called statically.
Example
Using getRoot()
<?php
$config = new Config();
$root =& $config->getRoot();
?>
Config::isConfigTypeRegistered
Config::isConfigTypeRegistered() – Returns TRUE if container is registered
Synopsis
require_once 'Config.php';
bool Config::isConfigTypeRegistered (
string $configType
)
Description
This method checks if the required container type exists in
$GLOBALS['CONFIG_TYPES'].
Parameter
-
string
$configType -
Type of config (php array, xml, inifile...)
Return value
bool - TRUE if registered, FALSE otherwise.
Note
This function can not be called statically.
Config::parseConfig
Config::parseConfig() – Parse datasource contents
Synopsis
require_once 'Config.php';
mixed &Config::parseConfig (
mixed $datasrc
, string $configType
, array $options = array()
)
Description
This method will parse the datasource given and fill the root Config_Container object with other Config_Container objects. It will return a reference to the root Config_Container object or a PEAR_Error if something went wrong.
Parameter
-
mixed
$datasrc -
Datasource to parse. For most containers, it is a file path. For the PHP array parser, it can be an array too.
-
string
$configType -
Type of configuration to parse
-
array
$options -
Options for the parser
Return value
object -
a reference to Config_Container object
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| PEAR_ERROR_RETURN | "Configuration type '$configType' is not registered in Config::parseConfig." | The config type must be registered for use by Config. | Use one of the standard config types, or register your custom container using Config::registerConfigType |
Other errors may be returned from the parser for the specific container you're using.
Note
This function can not be called statically.
Example
Using parseConfig()
<?php
$config = new Config();
$root =& $config->parseConfig('/path/to/file.php', 'phparray',
array('name' => 'conf'));
?>
Config::registerConfigType
Config::registerConfigType() – Registers a custom Config container
Synopsis
require_once 'Config.php';
bool Config::registerConfigType (
string $configType
, array $configInfo = false
)
Description
This method registers a new container type with the Config class.
Parameter
-
string
$configType -
The name of the configuration type.
-
array
$configInfo -
An array defining the file containing the container's class definition and the class name. The format for this array is as follows:
<?php $configInfo = array('path/to/Name.php', // The path to the source file for the class. 'Config_Container_Class_Name' // The name of the container class. ); ?>If omitted, the default values are:
<?php $configInfo = array("Config/Container/$configType.php", "Config_Container_$configType" ); ?>
Return value
mixed -
Returns TRUE on success,
PEAR_Error on failure.
Config::setRoot
Config::setRoot() – Set content of root Config_container object
Synopsis
require_once 'Config.php';
mixed Config::setRoot (
object &$rootContainer
)
Description
This method will replace the current child of the root Config_Container object by the given object.
Parameter
-
object
$rootContainer -
Container to be used as the first child of root
Return value
boolean -
Returns TRUE on success, FALSE on failure.
Note
This function can not be called statically.
Example
Using setRoot()
<?php
$container =& new Config_Container('section', 'conf');
$config = new Config();
$root =& $config->setRoot($container);
?>
Config::writeConfig
Config::writeConfig() – Write container content to datasource
Synopsis
require_once 'Config.php';
mixed Config::writeConfig (
mixed $datasrc
= null
, string $configType
= null
, array $options = array()
)
Description
This method will call the root Config_Container::writeDatasrc() method which in turn will try to write the Config contents to the datasource.
Parameter
-
mixed
$datasrc -
Datasource to write to
-
string
$configType -
Type of configuration for writer
-
array
$options -
Options for writer
Return value
mixed -
Returns TRUE on success,
PEAR_Error on failure.
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Example
This example shows how to convert a configuration from a php file which contains a php array to an xml file.
Using writeConfig()
<?php
$config = new Config();
$config->parseConfig(
'/path/to/file.php',
'phparray',
array('name' => 'conf')
);
$config->writeConfig( '/path/to/file.xml',
'xml',
array('name' => 'conf')
);
?>
Config_Container class
Config_Container::Config_Container
Config_Container::Config_Container() – Constructor
Synopsis
require_once 'Config/Container.php';
&Config_Container::Config_Container (
string $type = ''
, string $name = ''
, string $content = ''
, mixed $attributes
= null
)
Description
Creates a new Config_Container and returns it by reference.
Parameter
-
string
$type -
Type of container object, should be something among
'section','comment','directive','blank'.
-
string
$name -
Name of container object. The name is required for sections and directives, not for blanks or comments.
-
string
$content -
Content of container object. The content is used in directives and comments.
-
array
$attributes -
Array of attributes for container object. Optionally, you can add attributes to your container. These can be used by the chosen parser.
Return value
object - A reference to the created object.
Note
This function can not be called statically.
Config_Container::addItem
Config_Container::addItem() – Add item to this item.
Synopsis
require_once 'Config/Container.php';
object Config_Container::addItem (
object &$item
, string $where = 'bottom'
, object $target
= null
)
Description
This method will add a Config_Container child to the current container
children. Thus, addItem() can only be called
one a section type container. If a position is specified,
the object will be added at this position. If
'before' or 'after'
are specified as position, a target object is required.
The object will then be added before or after the target
object position in the current container.
Parameter
-
object
&$item -
a container object
-
string
$where -
choose a position
'bottom','top','after','before'
-
object
$target -
needed if you choose
'before'or'after'in$where.$targetmust be one of this container's children. ZendEngine2 will accept references with default. It will then be possible to have&$targetinstead.
Return value
object - A reference to the added object
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Example
Adding an item using addItem()
<?php
$section =& new Config_Container('section', 'conf');
$directive =& new Config_Container('directive', 'user', 'mansion');
$section->addItem($directive);
?>
Adding an item using addItem() and a position relative to another item
<?php
$section =& new Config_Container('section', 'conf');
$directive =& new Config_Container('directive', 'user', 'mansion');
$section->addItem($directive);
$comment =& new Config_Container('comment', null, 'Here goes my name');
$section->addItem($comment, 'before', $directive);
?>
Config_Container::countChildren
Config_Container::countChildren() – Count children of container
Synopsis
require_once 'Config/Container.php';
int Config_Container::countChildren (
string $type
= null
, string $name
= null
)
Description
This method will return the number of children this
container has. If either $name
or $type, it will affine its
search just to return the number of children
corresponding to these parameters.
Parameter
-
string
$type -
Type of children to count.
-
string
$name -
Name of children to count.
Return value
int - number of children found
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Config_Container::createBlank
Config_Container::createBlank() – Add blank line to item
Synopsis
require_once 'Config/Container.php';
objectConfig_Container::createBlank (
mixed $where = 'bottom'
, mixed $target
= null
)
Description
The current item must be a section. This is a helper method that calls createItem()
Parameter
-
string
$where -
Where to create the new item (
'top','bottom','before','after')
-
object
$target -
Required only if
'before'or'after'is used for$where
Return value
object - reference to new item
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Example
Create a new directive using createBlank()
<?php
$section =& new Config_Container('section', 'conf');
$directive =& $section->createDirective('user', 'mansion');
$section->createBlank('before', $directive);
?>
Config_Container::createComment
Config_Container::createComment() – Add comment to item
Synopsis
require_once 'Config/Container.php';
objectConfig_Container::createComment (
string $content = ''
, string $where = 'bottom'
, object $target
= null
)
Description
The current item must be a section. This is a helper method that calls createItem()
Parameter
-
string
$content -
Comment content
-
string
$where -
Where to create the new item (
'top','bottom','before','after')
-
object
$target -
Required only if
'before'or'after'is used for$where
Return value
object - reference to new item
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Example
Create a new directive using createComment()
<?php
$section =& new Config_Container('section', 'conf');
$section->createComment('Database Configuration');
?>
Config_Container::createDirective
Config_Container::createDirective() – Add directive to item
Synopsis
require_once 'Config/Container.php';
object Config_Container::createDirective (
string $name
, string $content
, mixed $attributes
= null
, string $where = 'bottom'
, mixed $target
= null
)
Description
The current item must be a section. This is a helper method that calls createItem()
Parameter
-
string
$name -
Name of new directive
-
string
$content -
Content of new directive
-
mixed
$attributes -
Directive attributes
-
string
$where -
Where to create the new item (
'top','bottom','before','after')
-
object
$target -
Required only if
'before'or'after'is used for$where
Return value
object - reference to new item
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Example
Create a new directive using createDirective()
<?php
$section =& new Config_Container('section', 'conf');
$section->createDirective('user', 'mansion');
?>
Config_Container::createItem
Config_Container::createItem() – Create new child for section item
Synopsis
require_once 'Config/Container.php';
object &Config_Container::createItem (
string $type
, mixed $item
, string $content
, array $attributes
= null
, string $where = 'bottom'
, object $target
= null
)
Description
This method must be called on a section, the created item can be anything. It adds a new child to the current item. If a position is specified, the child will be created at there. It is recommended to use the helper methods instead of calling this method directly.
Parameter
-
string
$type -
type of item:
directive,section,comment,blank...
-
mixed
$item -
item name
-
string
$content -
item content
-
array
$attributes -
item attributes
-
string
$where -
choose a position
'bottom','top','after','before'
-
object
$target -
needed if you choose
'before'or'after'for$where
Return value
object - reference to new item
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Example
Create some new items using createItem()
<?php
$section =& new Config_Container('section', 'conf');
$section->createItem('directive', 'user', 'root');
$section->createItem('directive', 'pass', 'root');
$header =& $section->createItem('comment', null, 'Database Configuration', 'top');
$section->createItem('blank', null, null, 'after', $header);
?>
Config_Container::createSection
Config_Container::createSection() – Add section to item
Synopsis
require_once 'Config/Container.php';
objectConfig_Container::createSection (
string $name
, array $attributes
= null
, string $where = 'bottom'
, object $target
= null
)
Description
Must be called on a section. This is a helper method that calls createItem()
Parameter
-
string
$name -
Name of new section
-
array
array $attributes -
Section attributes
-
string
$where -
Where to create the new item (
'top','bottom','before','after')
-
object
$target -
Required only if
'before'or'after'is used for$where
Return value
object - reference to new item
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Example
Create a new section using createSection()
<?php
$conf =& new Config_Container('section', 'MAIN');
$dbConf =& $conf->createSection('DB');
$dbConf->createDirective('user', 'mansion');
?>
Config_Container::getAttribute
Config_Container::getAttribute() – Get attribute value of item
Synopsis
require_once 'Config/Container.php';
mixed Config_Container::getAttribute (
string $attribute
)
Description
This method returns the value associated with the key attribute. To get all attributes, see method getAttributes().
Parameter
-
string
$attribute -
Attribute key
Return value
mixed - item's attribute value
Note
This function can not be called statically.
Config_Container::getAttributes
Config_Container::getAttributes() – Get item attributes
Synopsis
require_once 'Config/Container.php';
array Config_Container::getAttributes (
void
)
Description
This method returns an array containing the attributes of this container.
Return value
array - item's attributes
Note
This function can not be called statically.
Example
Using attribute
<?php
$attributes = array('id' => 'db', 'language' => 'en');
$section =& new Config_Container('section', 'main', null, $attributes);
$section->createDirective('authentication', 'test', array('type' => 'mysql',
'host' => 'localhost'));
echo $section->toString('phparray');
echo $section->toString('xml');
?>
Attributes are set for '@' key with php array type
<?php
$main['@']['id'] = 'db';
$main['@']['language'] = 'en';
$main['authentication']['#'] = 'test';
$main['authentication']['@']['type'] = 'mysql';
$main['authentication']['@']['host'] = 'localhost';
?>
Attributes are set the usual way with xml type
<?xml version="1.0" encoding="ISO-8859-1"?>
<main id="db" language="en">
<authentication type="mysql" host="localhost">
test
</authentication>;
</main>
Config_Container::getChild
Config_Container::getChild() – Return child object at specified index.
Synopsis
require_once 'Config/Container.php';
mixed Config_Container::getChild (
int $index
)
Description
Children are stored in an array. This method returns the Config_Container object at the specified index.
Parameter
-
integer
$index -
Child index
Return value
mixed - returns reference to child object or
FALSE if child does not exist
Note
This function can not be called statically.
Config_Container::getContent
Config_Container::getContent() – Get item content
Synopsis
require_once 'Config/Container.php';
mixed Config_Container::getContent (
void
)
Description
Accessor method. Returns the item content.
Return value
mixed - item's content
Note
This function can not be called statically.
Config_Container::getItem
Config_Container::getItem() – Tries to find specific items
Synopsis
require_once 'Config/Container.php';
mixed Config_Container::getItem (
string $type
= null
, string $name
= null
, mixed $content
= null
, array $attributes
= null
, int $index = -1
)
Description
This method tries to find the items that respond to the specified parameters.
This method can only be called on an object of type
'section'. Note that root is a section.
This method is not recursive and tries to keep the current structure.
Parameter
-
string
$type -
type of item:
directive,section,comment,blank...
-
string
$name -
item name
-
mixed
$content -
find item with this content
-
array
$attributes -
find item with attribute set to the given value
-
integer
$index -
index of the item in the returned object list. If it is not set, will try to return the last item with this name.
Return value
mixed - reference to item found or FALSE when not found
Note
This function can not be called statically.
Example
A few examples on how to find items using getItem()
<?php
// will return the last directive found
$directives =& $obj->getItem('directive');
// will return the last directive found with content 'root'
$directives =& $obj->getItem('directive', null, 'root');
// will return the fourth directive with name 'bar'
$directive_bar_4 =& $obj->getItem('directive', 'bar', null, null, 4);
// will return the last section named 'foo'
$section_foo =& $obj->getItem('section', 'foo');
// will return the last section with attribute 'id' set to 'db'
$section_foo =& $obj->getItem('section', 'foo', null, array('id' => 'db'));
?>
Config_Container::getItemIndex
Config_Container::getItemIndex() – Return item index in its parent children array
Synopsis
require_once 'Config/Container.php';
mixed Config_Container::getItemIndex (
void
)
Description
Children Config_Container objects are stored in an array. This method will return the index of this item in its parent array.
Return value
mixed - returns int or NULL if root object
Note
This function can not be called statically.
Config_Container::getItemPosition
Config_Container::getItemPosition() – Return item rank in its parent children array
Synopsis
require_once 'Config/Container.php';
int Config_Container::getItemPosition (
void
)
Description
Returns the item rank in its parent children array according to other items with same type and name.
Return value
mixed - returns int or NULL if root object
Note
This function can not be called statically.
Config_Container::getName
Config_Container::getName() – Get item name
Synopsis
require_once 'Config/Container.php';
string Config_Container::getName (
void
)
Description
Return the name of this item.
Return value
string - item's name
Note
This function can not be called statically.
Config_Container::getParent
Config_Container::getParent() – Return item parent object
Synopsis
require_once 'Config/Container.php';
object Config_Container::getParent (
void
)
Description
Returns the item parent object.
Return value
object - reference to parent object or NULL if root object
Note
This function can not be called statically.
Config_Container::getType
Config_Container::getType() – Get item type
Synopsis
require_once 'Config/Container.php';
string Config_Container::getType (
void
)
Description
Gets this item's type.
Return value
string - item type
Note
This function can not be called statically.
Config_Container::isRoot
Config_Container::isRoot() – Check for root item
Synopsis
require_once 'Config/Container.php';
bool Config_Container::isRoot (
void
)
Description
There is only one root item. It has no parent, no name, no content and is of type 'section'. The root item is not used in the parsers, only its children.
Return value
bool - TRUE if item is the root item
Note
This function can not be called statically.
Config_Container::removeItem
Config_Container::removeItem() – Deletes an item from the object
Synopsis
require_once 'Config/Container.php';
mixed Config_Container::removeItem (
void
)
Description
This method removes the current item. References to its children are removed as well. This method does not accept parameters yet.
Return value
boolean - TRUE if object was removed,
FALSE if not, or PEAR_Error if root
Note
This function can not be called statically.
Config_Container::searchPath
Config_Container::searchPath() – Finds a node using XPATH like format
Synopsis
require_once 'Config/Container.php';
mixed Config_Container::searchPath (
mixed $args
)
Description
This method tries to find an item by following a given path from the current container.
This method can only be called on an object of type
'section'. Note that root is a section.
This method is recursive.
This method takes as many parameters as is needed to define your path to the requested item.
The format is array (item1, item2, ..., itemN). Items can be strings or arrays. Strings will match
the item name, while arrays will match 'name' and/or 'attributes' properties of the requested item.
Parameter
-
mixed
$args -
Strings or arrays of item to match in the order they will be matched, separated by commas
Return value
mixed - reference to item found or FALSE when not found
Note
This function can not be called statically.
Example
Example for searchPath() usage
<?php
// Let's say our XML configuration looks like this:
// <config>
// <db>
// <user>root</user>
// <password>pass</user>
// <host>localhost</host>
// </db>
// </config>
$config = new Config();
$root =& $menuObj->parseConfig('db.xml', 'xml');
// Will return the password directive in db
$passObj =& $root->searchPath(array('config', 'db', 'password'));
?>
More complex example with attributes for searchPath()
<?php
// Let's say our XML configuration looks like this:
// <menu>
// <group id="company">
// <page id="news"/>
// <page id="jobs"/>
// </group>
// <group id="projects">
// <page id="project1"/>
// <page id="project2"/>
// </group>
// </menu>
$menuObj = new Config();
$root =& $menuObj->parseConfig('menu.xml', 'xml');
// Will return the container in menu which 'id' is set to 'projects'
$section =& $root->searchPath(array('menu', array('group', array('id' => 'projects'))));
// To get a page we could also use
$page =& $root->searchPath(array('menu',
array('group', array('id' => 'projects')),
array('page', array('id' => 'project2'))));
?>
Config_Container::setAttributes
Config_Container::setAttributes() – Set item attributes
Synopsis
require_once 'Config/Container.php';
void Config_Container::setAttributes (
array $attributes
)
Description
Attributes are stored in an array. They are used in some containers like PHP Array, XML, Apache. In IniFile or IniCommented containers, attributes are not used. See examples in getAttributes() method to have an idea of the attributes output. This method will replace existing attributes. Use updateAttributes() if you just want to change some of them.
Parameter
-
array
$attributes -
Array of attributes
Note
This function can not be called statically.
Config_Container::setContent
Config_Container::setContent() – Set item content
Synopsis
require_once 'Config/Container.php';
void Config_Container::setContent (
mixed $content
)
Description
Set this item's content.
Parameter
-
mixed
mixed $content -
Item's content
Note
This function can not be called statically.
Config_Container::setDirective
Config_Container::setDirective() – Set child directive content or create new directive
Synopsis
require_once 'Config/Container.php';
void Config_Container::setDirective (
string $name
, mixed $content
, int $index = -1
)
Description
This is an helper method that will first try to find the item with the desired name using getItem(). If the item is found, it will call its setContent() method. If not, it will just create a new directive at the bottom with the given name and content.
Parameter
-
string
$name -
Name of the directive to look for
-
mixed
$content -
New content, usually a string
-
integer
$index -
Index of the directive to set, in case there are more than one directive with the same name
Return value
object - Newly set directive
Note
This function can not be called statically.
Config_Container::setName
Config_Container::setName() – Set item name
Synopsis
require_once 'Config/Container.php';
void Config_Container::setName (
string $name
)
Description
Set this item's name.
Parameter
-
string
$name -
Item name
Note
This function can not be called statically.
Config_Container::setType
Config_Container::setType() – Set item type
Synopsis
require_once 'Config/Container.php';
void Config_Container::setType (
string $type
)
Description
Set this item's type.
Parameter
-
string
$type -
item type
Note
This function can not be called statically.
Config_Container::toArray
Config_Container::toArray() – Return key/value pair array of container and its children
Synopsis
require_once 'Config/Container.php';
array Config_Container::toArray (
void
)
Description
This method returns an array representation of the Config tree. The format is
<?php
$section[directive][index] = value
?>If the container has attributes, it will use '@' as key
for attributes and '#' for values.
index is here because multiple directives and sections can have the same name,
the toArray() method takes care of that.
Return value
array - an array representation of
the Config_Container tree
Note
This function can not be called statically.
Example
Using toArray()()
<?php
$attributes = array('id' => 'db', 'language' => 'en');
$section =& new Config_Container('section', 'main', null, $attributes);
$section->createDirective('authentication', 'one', array('type' => 'mysql'));
$section->createDirective('authentication', 'two', array('type' => 'oracle'));
$section->createDirective('permission', 'group');
var_dump($section->toArray());
?>
Resulting array with attributes and directives with same name or not
array(1) {
["main"]=>
array(3) {
["@"]=>
array(2) {
["id"]=>
string(2) "db"
["language"]=>
string(2) "en"
}
["authentication"]=>
array(2) {
[0]=>
array(2) {
["#"]=>
string(3) "one"
["@"]=>
array(1) {
["type"]=>
string(5) "mysql"
}
}
[1]=>
array(2) {
["#"]=>
string(3) "two"
["@"]=>
array(1) {
["type"]=>
string(6) "oracle"
}
}
}
["permission"]=>
string(5) "group"
}
}
Config_Container::toString
Config_Container::toString() – Return string representation
Synopsis
require_once 'Config/Container.php';
string Config_Container::toString (
string $configType
, array $options = array()
)
Description
This method will call the toString() method in the choosen config type. It will return a string representation of the Config_Container and its children.
Parameter
-
string
$configType -
Type of configuration used to generate the string
-
array
$options -
Specify special options used by the parser
Return value
string - the generated string
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Config_Container::updateAttributes
Config_Container::updateAttributes() – Update item attributes
Synopsis
require_once 'Config/Container.php';
void Config_Container::updateAttributes (
array $attributes
)
Description
If the specified attributes are already set, they are overwritten. New attributes are set. The ones that are not set in the given parameter array are left untouched.
Parameter
-
array
$attributes -
Array of attributes
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.
Config_Container::writeDatasrc
Config_Container::writeDatasrc() – Write item to file
Synopsis
require_once 'Config/Container.php';
boolean Config_Container::writeDatasrc (
mixed $datasrc
, string $configType
, array $options = array()
)
Description
By default, this method will write a new string generated with the toString() method to a file. If a writeDatasrc() method exists in the chosen config type, this method will be called instead. This allows for more flexibility and makes it possible to add your own save handlers.
Parameter
-
mixed
$datasrc -
Info on datasource such as path to the configuraton file or dsn...
-
string
$configType -
Type of configuration
-
array
$options -
Options for writer
Return value
boolean - TRUE on success
Throws
| Error code | Error value | Meaning | Solution |
|---|---|---|---|
| " |
Note
This function can not be called statically.