PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Creating Configurable Writers and Filters

If you find yourself needing to write your own log writers and/or filters, you can make them compatible with Zend_Log::factory() very easily.

At the minimum, you need to implement Zend_Log_FactoryInterface, which expects a static factory() method that accepts a single argument, $config, which may be either an array or Zend_Config object. If your log writer extends Zend_Log_Writer_Abstract, or your log filter extends Zend_Log_Filter_Abstract, you will pick this up for free.

Then, simply define mappings between the accepted configuration and any constructor arguments. As an example:

<?php
class My_Log_Writer_Foo extends Zend_Log_Writer_Abstract
{
    public function 
__construct($bar$baz)
    {
        
// ...
    
}

    public static function 
factory($config)
    {
        if (
$config instanceof Zend_Config) {
            
$config $config->toArray();
        }
        if (!
is_array($config)) {
            throw new 
Exception(
                
'factory expects an array or Zend_Config instance'
            
);
        }

        
$default = array(
            
'bar' => null,
            
'baz' => null,
        );
        
$config array_merge($default$config);

        return new 
self(
            
$config['bar'],
            
$config['baz']
        );
    }
}

Alternately, you could call appropriate setters after instantiation, but prior to returning the instance:

<?php
class My_Log_Writer_Foo extends Zend_Log_Writer_Abstract
{
    public function 
__construct($bar null$baz null)
    {
        
// ...
    
}

    public function 
setBar($value)
    {
        
// ...
    
}

    public function 
setBaz($value)
    {
        
// ...
    
}

    public static function 
factory($config)
    {
        if (
$config instanceof Zend_Config) {
            
$config $config->toArray();
        }
        if (!
is_array($config)) {
            throw new 
Exception(
                
'factory expects an array or Zend_Config instance'
            
);
        }

        
$writer = new self();
        if (isset(
$config['bar'])) {
            
$writer->setBar($config['bar']);
        }
        if (isset(
$config['baz'])) {
            
$writer->setBaz($config['baz']);
        }
        return 
$writer;
    }
}

Zend Framework