Using YAML with the Zend Framework

这篇文章介绍了如何在Zend Framework的config中使用yaml。出处

One of the many great components provided by the Zend Framework is Zend_Config. In a nutshell, this component allows you to access configuration data (from a file, array, etc) through a nested object property based interface. Out of the box, the component supports working with XML and INI files via theZend_Config_Ini and Zend_Config_Xml Config adapters.

If you’re familiar with frameworks like Ruby on Rails or Symfony however, you may notice that YAML support is missing. This is mostly because there is no one YAML parsing library for PHP. If you are willing to introduce another dependency to your application however, there is a really easy way to use Spyc to bridge YAML and Zend_Config. One of the nice things about the Zend_Config component is that it can take data right out of a PHP array (as opposed to an XML or INI file). This gives us quite a lot of flexibility, especially considering that Spyc returns parsed YAML data as a PHP array. Armed with this knowledge, the solution becomes really, really simple:

<?php
require_once 'Zend/Config.php';
require_once 'spyc.php';

$configFile = "config.yml";
$config = new Zend_Config(Spyc::YAMLLoad($confFile));
?>

Remarkably simple isn’t it? Now, given the YAML config file:

 webhost: www.example.com
 database:
     adapter: pdo_mysql
     host: db.example.com
     username: dbuser
     password: secret
     dbname: mydatabase

The above PHP code will create a config object that can then be used like this:

<?php
print $config->webhost;        // prints 'www.example.com'
print $config->database->host; // prints 'db.example.com'
?>

相关内容

5 Responses to “Using YAML with the Zend Framework”


  1. No Comments
  1. 1 Using YAML with the Zend Framework ·
  2. 2 Using YAML with the Zend Framework ·
  3. 3 The Triumph of Man over Machine ·
  4. 4 Etymotic Research etyBLU Dual-Mode Noise-Isolating Headset ·
  5. 5 Average Revenues That Mobile Ringtones Make Worldwide ·

Leave a Reply