Claudiu Persoiu

Blog-ul lui Claudiu Persoiu


Archive for 26 January 2010

Oracle to buy Sun – a new chapter

without comments

It seems like Oracle received the unconditional approval from EU to by Sun according to Yahoo! News.

About and year and a half ago I was considering the MySQL Certified Developer exam. Now I’ve become Sun MySQL Certified Developer and it seems like I’ll even become Oracle MySQL Certified Developer. And all of this with no extra charge! đŸ™‚

The good part is that we’ll become Oracle developers even if we don’t want or plan to (ok, is not exactly Oracle, but one of there products).

Written by Claudiu Persoiu

26 January 2010 at 9:57 PM

Posted in Diverse,MySQL

Tagged with , ,

Factory method pattern using PHP 5.3 and late static bindings

without comments

Factory method design pattern introduced by GoF (Gang of Four) which I’ve talked about in a previous blog, has the base idea of a method that generates objects. Most implementations are “poor”, because they use a lot of hard-coding for the factory (just like me in the previous blog).

PHP 5.3 offers the possibility of a very interesting implementation using “Late static bindings“.

The classes from which the objects will be generated are:

// abstract base class that will be inherited
abstract class Drink {

    // ingredients
    protected $ingredients;

    // public method for producing the drink
    abstract public function MakeDrink();
}

// a child class for tea
class Tea_Drink extends Drink {

    // ingredients for tea
    protected $ingredients = array('tea', 'sugar', 'mink', 'water');

    // make tea
    public function MakeDrink() {

        // make tea
    }
}

// another class for Bloody Mary
class BloodyMary_Drink extends Drink {

    // ingredients for Bloody Mary
    protected $ingredients = array('votka', 'salt', 'tomato juice');

    // make Bloody Mary
    public function MakeDrink() {

        // make BloodyMary

    }
}

The idea is to have an abstract factory class to extend as simple as possible when creating each new factory class.

PHP 5

In PHP 5 the class will look something like this:

// abstract Factory class
abstract class absFactory {

    // name of the base class
    static protected $base_class = '';

    // factory method
    public static function getInstance($type) {

        // name of the resulting class
        $class_name = $type . '_' . self::$base_class;

        // check if class exists
        // here you can add an autoloader
        if(!class_exists($class_name)) {
            throw new Exception( 'Class ' . $class_name . ' not loaded!');
        }

        // check to see if the class inherits the base class
        if(!is_subclass_of($class_name, self::$base_class)) {
            throw new Exception(
                'Class ' . $class_name . ' is not a child of ' . self::$base_class
            );
        }

        // new object
        return new $class_name;

    }

}

Because the getInstance() method is static the property will be static too.

If we try:

class DrinkFactory extends absFactory {

    static protected $base_class = 'Drink';
}

try {

    $obj = DrinkFactory::getInstance('Tea');

} catch (Exception $e) {

    echo $e->getMessage();
}

The output will be:

Class Tea_ not loaded!

Because of the “self”, we can’t just call the method using the child class because the value of $base_class will be “” and not “Drink”, we must overwrite the getInstance() method. Which is quite “complicated”.

A working version in PHP 5 will be:

class DrinkFactory extends absFactory {

    public static function getInstance($type) {

        self::$base_class = 'Drink';

        // factory method of the base factory class
        parent::getInstance($type);

    }

}

try {

    $obj = DrinkFactory::getInstance('Tea');

} catch (Exception $e) {

    echo $e->getMessage();
}

But is not exactly “elegant”.

PHP 5.3

Here we have “Late static bindings”, which is basically introducing the work “static”.

The base factory class will look something like this:

// abstract Factory class
abstract class absFactory {

    // name of the base class
    static protected $base_class = '';

    // factory method
    public static function getInstance($type) {

        // name of the resulting class
        $class_name = $type . '_' . static::$base_class;

        // check if class exists
        // here you can add an autoloader
        if(!class_exists($class_name)) {
            throw new Exception( 'Class ' . $class_name . ' not loaded!');
        }

        // check to see if the class inherits the base class
        if(!is_subclass_of($class_name, static::$base_class)) {
            throw new Exception(
                'Class ' . $class_name . ' is not a child of ' . static::$base_class
            );
        }

        // new object
        return new $class_name;

    }

}

The differences from the PHP 5 are marked with bold. A change so small allows us to create a much “nicer” factory class:

class DrinkFactory extends absFactory {

     static protected $base_class = 'Drink';

}

try {

    $obj = DrinkFactory::getInstance('Tea');

} catch (Exception $e) {

    echo $e->getMessage();
}

Basically in this version only the relevant property in this context is overwritten.

Written by Claudiu Persoiu

24 January 2010 at 5:46 PM

Posted in Design patterns,PHP

Tagged with , , ,

Factory method design patten in PHP

without comments

An creational design pattern, which represents an solution for generation objects without specifying the class name. Virtually all methods that generate objects are particular implementations of the Factory Method pattern.

Motivation:

A motivation for this choice is that the creation of the object is delegated to the factory method.

Diagram:

factory method pattern

Implementation:
The classes that generates the objects, the common class to extend and the class with the factory method:

// the common class to be extended
abstract class OutputBase {
     // output the necessary headers
     abstract public function header();

     // resulting body
     abstract public function body($data);

}

// class for XML ouput
class XMLOutput extends OutputBase {

     // output XML header
     public function header() {
          header('content-type: text/xml');
     }

     // xml document
     public function body($data) {
          $res = '';

          $res .= '';

          foreach ($data as $root => $item) {

               $res .= '';

               foreach ($item as $key => $val) {
                    $res .= '<'.$key.'>'.$val.'';
               }

               $res .= '';
          }

          $res .= '';

          return $res;

     }

}

// class for CSV output
class CSVOutput extends OutputBase {

     // output CSV header
     public function header() {
          header("Content-type: text/plain");
     }

     // CSV body
     public function body($data) {
          $res = '';

          $keys = array_keys($data[0]);

          foreach ($keys as $key) {
               $res .= '"'.$key.'";';
          }
          $res .= "\r\n";

          foreach ($data as $item) {
               foreach ($item as $val) {
                    $res .= '"'.$val.'";';
               }

               $res .= "\r\n";
          }

          return $res;
     }
}

// the factory method class
// is abstract so it wont be instantiated
abstract class OutputFactory {

     // constant for XML type
     const XML = 1;

     // constant for CSV type
     const CSV = 2;

     // static factory method
     public static function getInstance($type) {
          // depending which constant was received as a parameter
          // one of the objects will be returned
          switch ($type) {
               case self::XML :
                    return new XMLOutput();
               break;

               case self::CSV :
                    return new CSVOutput();
               break;
          }

          // if the value received as a parameter is not one of the constants
          // an exception will be thrown
          throw new Exception('Invalid class type!');
     }

}

Example:

// the data
$data = array(
               array(
                    'a' => 1,
                    'b' => 2,
                    'c' => 3
                    ),
               array(
                    'a' => 4,
                    'b' => 5,
                    'c' => 6
                    )
          );

// try-catch block in case of an exception
try {
     // generation the object
     $obj = OutputFactory::getInstance(OutputFactory::XML);

     // output headers
     $obj->header();

     // display body
     echo $obj->body($data);

} catch (Exception $e) {

     $e->getMessage();

}

Written by Claudiu Persoiu

23 January 2010 at 6:21 PM

Posted in Design patterns

Tagged with ,

Another year has passed and PHP 6 is still not here…

without comments

Another year has passed and PHP 6 is still not here…

But that’s not exactly news, is the 4-th year when this long awaited version is not released. Not for nothing is called the most awaited version.

But overall it was a good year for the community, even though we still don’t have native Unicode in a stable version now we have all other awaited features in PHP 5.3, which will probably need another few years to become used on a large scale.

Even though everyone was expecting last year for Oracle to enter in full force on medium and small database market by purchasing Sun, enlarging it’s already well established  portfolio on the enterprise market. It seems that it was not to be, CE is still analyzing the deal.

However MySQL is not what it used to be 5-6 years ago, when nobody dared to use it for enterprise products. This days MySQL is a product ready to be used in both small and large products that require a lot of scalability.

But back to the year that just ended, it was a full year, even with this economic crises.

Written by Claudiu Persoiu

13 January 2010 at 8:30 AM

Posted in Diverse,MySQL,PHP

Tagged with , ,