A.4. Universal Constructor

All __construct() method signatures in Solar are identical to each other. They have exactly one parameter: an associative array. That array is then merged with values from the config file and the default class configuration. The merged values are retained in the protected $_config property used in all classes descended from the Solar_Base class.

Most classes in the PHP world use a sequential set of parameters for constructors; e.g., if you wanted to specify three pieces of information for a constructor, you would do something like the following.

<?php
class Normal_Example {
    protected $_a = null;
    protected $_b = null;
    protected $_c = null;
    public function __construct($a, $b, $c)
    {
        $this->_a = $a;
        $this->_b = $b;
        $this->_c = $c;
    }
}

// configure and instantiate a Normal_Example object
$example = new Normal_Example('one', 'two', 'three')

In comparison, Solar classes are constructed and instantiated like this:

<?php
class Solar_Example extends Solar_Base {
    // the default config array is named for the class with
    // an underscore prefix.  this lets us collect the parent
    // config defaults without them overwriting each other.
    protected $_Solar_Example = array(
        'a' => null,
        'b' => null,
        'c' => null,
    );
    
    public function __construct($config = null)
    {
        // let Solar_Base merge the config values from
        // the parents, and from the config file
        parent::__construct($config);
        
        // use the merged values in $this->_config to
        // set our property values
        $this->_a = $this->_config['a'];
        $this->_b = $this->_config['b'];
        $this->_c = $this->_config['c'];
    }
}

// configure and instantiate an Solar_Example object
$params = array(
    'a' => 'one',
    'b' => 'two',
    'c' => 'three'
);

$example = Solar::factory('Solar_Example', $params);

Why do things this way? The idea is to make it easy to read data from a config file and automatically configure object instances through a lazy-load registry, concrete factory, or other programmatic means. When every constructor is the same, you never need to keep track of which classes use which parameters in which order.



Local