Ransford Okpoti's Blog

18 March, 2012

Creating Dynamic Log Files In Zend Framework (ZF)

Filed under: PHP — Tags: , — ranskills @ 11:58 am

The motivation for wanting to do something like this could be any of the following:

  • You want to have separate logs depending on the context (i.e. application, testing, development, etc) in which the application is being run and you do not want to inherit a context and override some values in another context in the configuration file.
  • If your application builds huge log files and, as a result, you want to partition the logs into, say, daily, weekly, monthly, yearly, etc. logs

Below is a typical configuration in the application.ini file.

[application]
; Loggers
resources.log.stream.writerName             = "Stream"
resources.log.stream.writerParams.stream    = APPLICATION_PATH "/../data/logs/application.log"
resources.log.stream.writerParams.mode      = "a"
resources.log.stream.filterName             = "Priority"
resources.log.stream.filterParams.priority  = 4

The problem can easily be overcome by adding the highlighted lines to the configuration file, these settings will be used in the bootstrap file to create the log files.

; Loggers
resources.log.stream.writerName             = "Stream"
resources.log.stream.writerParams.stream    = APPLICATION_PATH "/../data/logs/application"
resources.log.stream.writerParams.mode      = "a"
resources.log.stream.filterName             = "Priority"
resources.log.stream.filterParams.priority  = 4

log.path               = APPLICATION_PATH "/../data/logs"
log.partitionStrategy  = "context"
log.partitionFrequency = "weekly"

New Entries Explained

log.path
Specifies the location/directory where the files would be created. NOTE: Linux users have to make sure the appropriate read/write permissions are set.
log.partitionStrategy
Defaults to context which denotes that log files will be prefixed with the context, or application environment, as is know in ZF, (e.g., production, development, testing , etc.) in which the application is being run.
log.partitionFrequency
Specifies when new log files get created and take on any of the following values: daily, weekly, monthly and yearly.

Next, in the Bootstrap.php, add _initLog()function as show below to dynamically create the log files based on the customized settings we provided in the application.ini.
The function simply alters the file name for the Stream logger by appending a unique string to the selected base file name based on the log.partitionFrequency value.

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

    protected function _initLog() {
        $options = $this->getOption('resources');

        $partitionConfig = $this->getOption('log');
        $logOptions = $options['log'];

        $baseFilename = $logOptions['stream']['writerParams']['stream'];
        if ($partitionConfig['partitionStrategy'] == 'context'){
            $baseFilename = $partitionConfig['path'].'/'.APPLICATION_ENV;
        }

        $logFilename = '';
        switch(strtolower($partitionConfig['partitionFrequency'])){
            case 'daily':
                $logFilename = $baseFilename.'_'.date('Y_m_d');
                break;

            case 'weekly':
                $logFilename = $baseFilename.'_'.date('Y_W');
                break;

            case 'monthly':
                $logFilename = $baseFilename.'_'.date('Y_m');
                break;

            case 'yearly':
                $logFilename = $baseFilename.'_'.date('Y');
                break;

            default:
                $logFilename = $baseFilename;

        }

        $logOptions['stream']['writerParams']['stream'] = $logFilename;

        $logger = Zend_Log::factory($logOptions);
        Zend_Registry::set('logger', $logger);

        return $logger;
    }
}

26 May, 2011

How to use PHP’s __autoload

Filed under: PHP — ranskills @ 4:05 pm

Classes used in this posting may refer to classes or interfaces where appropriate.

Ever wondered if there could be a more appropriate way to include dependent files into other PHP files other than using multiple include or require language constructs? Well, wonder no more, the __autoload magic function in PHP5 comes to the rescue. In simple words, this method/function gets invoked anytime the execution reaches a line containing a class or an interface for which the interpreter does not know of it’s existence either because it has not been defined in the same file or it’s been defined in a separate file ,but has not been included in the current executing script/file.

The __autoload function allows for the lazy loading of classes, the classes only gets loaded when they are needed.

Lets look at some examples. In the code below, the __autoload function will never be called because there is only one class which has been defined within the file itself, so the interpreter knows of its definition.

<?php
function __autoload($class){
    echo 'Loading Interface/Class with name '.$class;
}

class Address{
}
?>

With this second example, the PHP interpreter does not known the definition of the interface IAddress, so it calls the __autoload function passing it the name IAddress, but since the function does not do anything yet except output the string Loading Interface/Class with name IAddress , and raises the error:

Interface ‘IAddress’ not found in path/to/script

<?php
function __autoload($class){
    echo 'Loading Interface/Class with name '.$class;
}

class Address implements IAddress{

}
?>

If the definition of the interface IAddress was in a different file say IAddress.php and in the same directory as our current script, we would have had the following code below.

<?php
include_once 'IAddress.php';
class Address implements IAddress{

}
?>

Lets look at another script which requires several classes defined in the classes directory.

<?php
include_once 'classes/Address.php';
include_once 'classes/Person.php';
include_once 'classes/ShoppingCart.php';

$addr = new Address();
?>

From the above code, it should hit you that if your script needs several classes/interfaces, that have rightly been, defined in their own separate files, then you’ll have to manually include all of them, so you could end up with 15 or 20 or more lines of include_once/require_once in your code. This definitely doesn’t sound exciting, you could argue that you could add the classes directory to your include path using the set_include_path function, but it still doesn’t take away the fact that you’ll have to include the class files using any of the file inclusion statements.

Now, lets solve the simple problem above before moving to a more complex scenario.

To quickly solve this, all we do is to remove all the include/require lines from the above code and add the __autoload function.

<?php
function autoLoader($class_name){
    include_once('classes/'.$class.'.php');
}

spl_autoload_register('autoLoader');

$addr = new Address();
?>

[notice type=attention]
For this to work, the class name should lead us to easily predict the name of the file to be included i.e., the class name must be part of the file name. So, a class named Address stored in
address.php,
address.class.php,
address.inc.php or
class.address.php
is more helpful than storing it in some_unrelated_name.php .
[/notice]
This works perfectly now, but it won’t work in all scenarios because

1. All classes may not be in a single directory called classes, unless you decide to do it so.

2. All classes may not be named in this format: class_name.php eg. Address.php, Person.php, etc. What happens if there are mixed class naming formats like Address.class.php, class.Address.php, Address.inc.php or any other format that the developer(s) of the class used.

While we are looking at situations that might break our seemingly wonderful solution to the class file inclusion nightmare, lets look at a class name like Zend_Log, Log_display or Archive_Tar, you can quickly take a look at the class names in the PEAR package/directory in relation to the directory they are defined in. The naming convention adopted was to solve the problem of class name clashes. The naming convention is: [directory_]+class
where the + implies that there must be at least one directory before the class name.
Here, the naming gives information about the directory that contains the actual class eg. here are some class names and their implied locations

Zend_Log -> Zend/Log.php

Calendar_Month_Weekdays -> Calendar/Month/Weekdays.php

Log_display -> Log/display.php

To solve this, we define our own autoloader function to try and load the required classes/interfaces. The code is shown below. Lets name the script autoloader.php

<?php
/**
 *
 * @param string $className Class or Interface name automatically
 *              passed to this function by the PHP Interpreter
 */
function autoLoader($className){
    //Directories added here must be relative to the script going to use this file
    $directories = array(
      '',
      'classes/'
    );

    //Add your file naming formats here
    $fileNameFormats = array(
      '%s.php',
      '%s.class.php',
      'class.%s.php',
      '%s.inc.php'
    );

    // this is to take care of the PEAR style of naming classes
    $path = str_ireplace('_', '/', $className);
    if(@include_once $path.'.php'){
        return;
    }
    
    foreach($directories as $directory){
        foreach($fileNameFormats as $fileNameFormat){
            $path = $directory.sprintf($fileNameFormat, $className);
            if(file_exists($path)){
                include_once $path;
                return;
            }
        }
    }
}

spl_autoload_register('autoLoader');
?>

Now, all we have to do is to include autoloader.php into any of the scripts what will be making use of other classes/interfaces.

<?php
include_once 'autoloader.php';

$addr = new Address();
$shoppingCart = new ShoppingCart();
$person = new Person();

$person->setAddress($addr);
$person->setShoppingCart($shoppingCart);

?>

[notice type=download]
Download autoloader.php
[/notice]

How To Add A Custom Id Generation Strategy To Doctrine 2.1

Filed under: PHP — Tags: — ranskills @ 12:50 pm

UPDATE: The UUID Id Generation feature has now been added to Doctrine now, refer to the documentation

Object-Relational Mapping (ORM) has caught up with PHP. In case you have been living under a rock, here’s the list of the popular ORM solutions in PHP:

With the advent of Doctrine 2.0.0 (which at the time of writing this article is at Beta 2), which requires a minimum of PHP version 5.3, our domain objects (models) are now free from subclassing a mandatory superclass as imposed by its predecessors (previous versions before 2.0.0).
Below is a code snippet of a User model as would be implemented in earlier versions of Doctrine before version 2.0.0.

class User extends BaseUser
{
}

The 2.0 version is totally different in that it now resembles the popular ORM solution in Java, Hibernate.
Now your entity classes can be a plain old PHP object (POPO) with annotations providing persistence information on how to update the persistent store with the field values of an instance of the entity class. There is also the option of using YAML, XML, or plain PHP to provide persistence information to the persistence manager.

I will just stick to the topic of this post by not delving into the nitty-gritties of how to setup and use Doctrine because it can boast of one of the best documentations, and tutorials on how to get it up and running.

In this artcle, we will be looking at how to use a UUID or GUID, for the primary keys of our entities instead of the traditional auto incremented unsigned numeric values, to demonstrate how easy it is to add a custom id generation strategy to your ever popular Doctrine.

If you ever decide to use a Universally Unique Identifier (UUID) or Globally Unique Identifier (GUID) as the primary keys for tables in your database, for various reasons such as having an application used by various clients in various geographical locations in a disconnected environment where each client has its own copy of the database with the likelihood of the various databases been merged into a centralized database server in the near future, then this would be particularly helpful.

1. In order to stick to the adopted convention, id generation classes reside in the Doctrine\ORM\Id namespace or package or directory (or which ever jargon you prefer to use), we let our UUIDGenerator extend the AbstractIdGenerator abstract class.

Below is the AbstractIdGenerator abstract class provided by Doctrine to be extended by all id generation strategies.

namespace Doctrine\ORM\Id;

use Doctrine\ORM\EntityManager;

abstract class AbstractIdGenerator
{
    abstract public function generate(EntityManager $em, $entity);

    public function isPostInsertGenerator()
    {
        return false;
    }
}

Now, we have to provide an implementation for the generate abstract method, and let the isPostInsertGeneration return false since the id will be generated and assigned to the entity/model before insertion into the related table. Various implementations of the UUID algorithm can be found on the net, so if you decide to implement your own version or find a more reliable and appropriate one just feel free to plug it in. By the way, I’ve even forgot the source of the UUID implementation am using in this article, so please forgive me if i haven’t credited the author(s) of the code.

Create UUIDGenerator.php in Doctrine\ORM\Id with the code below.

/**
 * @author Ransford Okpoti
 */
namespace Doctrine\ORM\Id;

use Doctrine\ORM\EntityManager;

class UUIDGenerator extends AbstractIdGenerator {
    /**
     * Generates an ID for the given entity.
     *
     * @param object $entity
     * @return string
     * @override
     */
    public function generate(EntityManager $em, $entity) {
        return self::v4();
    }

    /**
     * @return boolean
     * @override
     */
    public function isPostInsertGenerator() {
        return false;
    }
    

    public static function v3($namespace, $name) {
        if(!self::is_valid($namespace)) return false;

        // Get hexadecimal components of namespace
        $nhex = str_replace(array('-','{','}'), '', $namespace);

        // Binary Value
        $nstr = '';

        // Convert Namespace UUID to bits
        for($i = 0; $i < strlen($nhex); $i+=2) {
            $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
        }

        // Calculate hash value
        $hash = md5($nstr . $name);

        return sprintf('%08s-%04s-%04x-%04x-%12s',

                // 32 bits for "time_low"
                substr($hash, 0, 8),

                // 16 bits for "time_mid"
                substr($hash, 8, 4),

                // 16 bits for "time_hi_and_version",
                // four most significant bits holds version number 3
                (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000,

                // 16 bits, 8 bits for "clk_seq_hi_res",
                // 8 bits for "clk_seq_low",
                // two most significant bits holds zero and one for variant DCE1.1
                (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

                // 48 bits for "node"
                substr($hash, 20, 12)
        );
    }

    public static function v4() {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

                // 32 bits for "time_low"
                mt_rand(0, 0xffff), mt_rand(0, 0xffff),

                // 16 bits for "time_mid"
                mt_rand(0, 0xffff),

                // 16 bits for "time_hi_and_version",
                // four most significant bits holds version number 4
                mt_rand(0, 0x0fff) | 0x4000,

                // 16 bits, 8 bits for "clk_seq_hi_res",
                // 8 bits for "clk_seq_low",
                // two most significant bits holds zero and one for variant DCE1.1
                mt_rand(0, 0x3fff) | 0x8000,

                // 48 bits for "node"
                mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }

    public static function v5($namespace, $name) {
        if(!self::is_valid($namespace)) return false;

        // Get hexadecimal components of namespace
        $nhex = str_replace(array('-','{','}'), '', $namespace);

        // Binary Value
        $nstr = '';

        // Convert Namespace UUID to bits
        for($i = 0;
        $i < strlen($nhex);
        $i+=2) {
            $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
        }

        // Calculate hash value
        $hash = sha1($nstr . $name);

        return sprintf('%08s-%04s-%04x-%04x-%12s',

                // 32 bits for "time_low"
                substr($hash, 0, 8),

                // 16 bits for "time_mid"
                substr($hash, 8, 4),

                // 16 bits for "time_hi_and_version",
                // four most significant bits holds version number 5
                (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,

                // 16 bits, 8 bits for "clk_seq_hi_res",
                // 8 bits for "clk_seq_low",
                // two most significant bits holds zero and one for variant DCE1.1
                (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

                // 48 bits for "node"
                substr($hash, 20, 12)
        );
    }

    public static function is_valid($uuid) {
        return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?'.
                '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1;
    }

}

2. Next, add GENERATOR_TYPE_UUID = 6, just ensure that the assigned number is unique within the other GENERATOR_TYPE constants, to Doctrine\ORM\Mapping\ClassMetadataInfo.php

const GENERATOR_TYPE_UUID = 6;

3. Finally, we need to add our UUID generation strategy to the list of provided generation strategies. Go to the completeIdGeneratorMapping function in Doctrine\ORM\Mapping\ClassMetadataFactory.php, and add the code below to the switch condition just before the default keyword.

            case ClassMetadata::GENERATOR_TYPE_UUID:
                $class->setIdGenerator(new \Doctrine\ORM\Id\UUIDGenerator());
                break;

I guess you are expecting a step 4? But am sorry to disappoint you, that is all it takes to accomplish our task. We can now make use of UUIDs as demonstrated through the use of annotations below:

/**
 * @Entity
 */
class User{
    /**
     *
     * @Id
     * @Column(type="string", length=36)
     * @GeneratedValue(strategy="UUID")
     */
    private $id;
}

Need I remind you that the downside of this approach is that you’ll have to repeat this process each time you decide to upgrade to a higher version, since Doctrine does not implicitly have UUIDs as one of its id generation strategies and there is no convenient way to programmatically register an id generation strategy at runtime. In my honest opinion, this 2 minutes step is well worth the effort.

28 July, 2009

How to Convert A Number To Words In PHP

Filed under: PHP — ranskills @ 4:48 pm

There comes a time when you really, really want a library to get a function/task performed for you and the results of your search on the internet does not give you what you actually want. Not in this case, am sure when you google the topic you should get a couple of interesting information, but the point i want to establish is that, being a little inquisitive to find out what is under the hood will help you know how the small small pieces join together to fulfill your needs.
The purpose of this posting is to give an insight into the PHP language by looking at variable definition, some control structures, classes and some inbuilt functions.

Naming variables in PHP is not all that different from other programming languages like Java, C# and the likes, the only exception is that all variables must start with the dollar sign, $, as demonstrated in the examples below.
The data type of a variable is determined by what value it holds and as a result you are not allowed to specify a variable’s data type before using it so you won’t find something like this anywhere

int $age = 30;

This is an example of a valid PHP code snippet

<?php
// this is a comment
/*
this is a multi-line comment
*/

$email = <a href=<a href="mailto:'person@nowhere.com'">mailto:'person@nowhere.com'</a>>'person@nowhere.com'</a>; // a string variable
$year = 2010; // an integer variable

/* a reference variable provided the class Company
has already been defined */
$company = new Company();
?>

Syntactically, PHP’s control structures and class definitions are just like their counterparts in the other modern languages such as Java and C#.

<?php

/**
 * A demo of class definition.
 *
 * @package clients
 * @author ranskills <a href=<a href="mailto:person@nowhere.com">mailto:person@nowhere.com</a>>person@nowhere.com</a>
 */
class Company {

    public static $numOfInstances = 0; // Class variable
    private $name; // Instance variable

    public function __construct($name) {
        self::$numOfInstances++;
        $this->name = trim($name);
    }

    /**
     * Getter method for the name attribute
     * @return string the name of the company
     */
    public function getName() {
        return $this->name;
    }

}
?>

Another interesting thing, is the concept of associative arrays which allows you to use strings to index your arrays. eg.

<?php

$countries = array(
    // index => value
    'gh' => 'Ghana',
    'sa' => 'South Africa'
);
?>

Now, lets look at some codes to convert any integer to it’s equivalent in words in English.

<?php

// Yes, you can create your own exceptions in PHP
class ArrayIndexOutOfBoundsException extends Exception {

    function __construct($message, $code = 0) {
        parent::__construct($message, $code);
    }

}

class Integer {

    public function toText($amt) {
        if (is_numeric($amt)) {
            echo '' . number_format($amt, 0, '.', ',') . '';
            $sign = $amt > 0 ? '' : 'Negative ';
            return $sign . $this->toQuadrillions(abs($amt));
        } else {
            throw new Exception('Only numeric values are allowed.');
        }
    }

    private function toOnes($amt) {
        $words = array(
            0 => 'Zero',
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
            4 => 'Four',
            5 => 'Five',
            6 => 'Six',
            7 => 'Seven',
            8 => 'Eight',
            9 => 'Nine'
        );

        if ($amt >= 0 && $amt < 10)
            return $words[$amt];
        else
            throw new ArrayIndexOutOfBoundsException('Array Index not defined');
    }

    private function toTens($amt) { // handles 10 - 99
        $firstDigit = intval($amt / 10);
        $remainder = $amt % 10;

        if ($firstDigit == 1) {
            $words = array(
                0 => 'Ten',
                1 => 'Eleven',
                2 => 'Twelve',
                3 => 'Thirteen',
                4 => 'Fourteen',
                5 => 'Fifteen',
                6 => 'Sixteen',
                7 => 'Seventeen',
                8 => 'Eighteen',
                9 => 'Nineteen'
            );

            return $words[$remainder];
        } else if ($firstDigit >= 2 && $firstDigit <= 9) {
            $words = array(
                2 => 'Twenty',
                3 => 'Thirty',
                4 => 'Fourty',
                5 => 'Fifty',
                6 => 'Sixty',
                7 => 'Seventy',
                8 => 'Eighty',
                9 => 'Ninety'
            );

            $rest = $remainder == 0 ? '' : $this->toOnes($remainder);
            return $words[$firstDigit] . ' ' . $rest;
        }
        else
            return $this->toOnes($amt);
    }

    private function toHundreds($amt) {
        $ones = intval($amt / 100);
        $remainder = $amt % 100;

        if ($ones >= 1 && $ones < 10) {
            $rest = $remainder == 0 ? '' : $this->toTens($remainder);
            return $this->toOnes($ones) . ' Hundred ' . $rest;
        }
        else
            return $this->toTens($amt);
    }

    private function toThousands($amt) {
        $hundreds = intval($amt / 1000);
        $remainder = $amt % 1000;

        if ($hundreds >= 1 && $hundreds < 1000) {
            $rest = $remainder == 0 ? '' : $this->toHundreds($remainder);
            return $this->toHundreds($hundreds) . ' Thousand ' . $rest;
        }
        else
            return $this->toHundreds($amt);
    }

    private function toMillions($amt) {
        $hundreds = intval($amt / pow(1000, 2));
        $remainder = $amt % pow(1000, 2);

        if ($hundreds >= 1 && $hundreds < 1000) {
            $rest = $remainder == 0 ? '' : $this->toThousands($remainder);
            return $this->toHundreds($hundreds) . ' Million ' . $rest;
        }
        else
            return $this->toThousands($amt);
    }

    private function toBillions($amt) {
        $hundreds = intval($amt / pow(1000, 3));
        /* Note:taking the modulos results in a negative value, but
          this seems to work pretty fine */

        $remainder = $amt - $hundreds * pow(1000, 3);

        if ($hundreds >= 1 && $hundreds < 1000) {
            $rest = $remainder == 0 ? '' : $this->toMillions($remainder);
            return $this->toHundreds($hundreds) . ' Billion ' . $rest;
        }
        else
            return $this->toMillions($amt);
    }

    private function toTrillions($amt) {
        $hundreds = intval($amt / pow(1000, 4));
        $remainder = $amt - $hundreds * pow(1000, 4);

        if ($hundreds >= 1 && $hundreds < 1000) {
            $rest = $remainder == 0 ? '' : $this->toBillions($remainder);
            return $this->toHundreds($hundreds) . ' Trillion ' . $rest;
        }
        else
            return $this->toBillions($amt);
    }

    private function toQuadrillions($amt) {
        $hundreds = intval($amt / pow(1000, 5));
        $remainder = $amt - $hundreds * pow(1000, 5);

        if ($hundreds >= 1 && $hundreds < 1000) {
            $rest = $remainder == 0 ? '' : $this->toTrillions($remainder);
            return $this->toHundreds($hundreds) . ' Quadrillion ' . $rest;
        }
        else
            return $this->toTrillions($amt);
    }

}

$obj = new Integer();

echo $obj->toText(5234567);
echo $obj->toText(-4191770001230128);
?>

This is the output of the above code when run

5,234,567
Five Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven

-4,191,770,001,230,128
Negative Four Quadrillion One Hundred Ninety One Trillion Seven Hundred Seventy Billion One Million Two Hundred Thirty Thousand One Hundred Twenty Eight

With this knowledge, you can attempt to write a program to convert an amount to words including the name of the currency.

Blog at WordPress.com.