I’ve learned a lot from transitioning from PHP to Ruby on Rails. One thing I loved about Rails was the separation of configuration and code. Rails stores it’s database configuration into a small text file written in YAML and organizes this in it’s own config folder. The following is about how I used YAML in PHP to better organize my code and framework files.
Example:
// Load Configuration
$config_path = PHP_PATH."/config/config.yml";
$class_path = PHP_PATH."/classes/spyc.php";
if (file_exists($config_path) && file_exists($class_path)) {
include $class_path;
$yaml = new Spyc;
$config = $yaml->YAMLLoad($config_path);
} else {
exit("The configuration file is missing.");
}
Spyc, “A simple YAML loader/dumper class for PHP,” is an open-source class for PHP that parses and stores the contents of a YAML file to an array. The line $yaml = new Spyc; creates an instance of the Spyc class, and the line $config = $yaml->YAMLLoad($config_path); stores the contents of the config.yml to the array $config. That’s all there is to it!
For more information about Spyc and to download the class, visit code.google.com/p/spyc.