Using PHP’s Imagick class to convert a CMYK jpeg to RGB

Having trouble with Imagick’s lack of documentation? Looking for a way to convert jpegs from CMYK to RGB that doesn’t use the command line? I just posted a solution for using PHP’s Imagick class to convert jpegs from CMYK to RGB on the Offshoot Blog. Click here to check it out.

October 25, 2008 at 10:18 pm Leave a comment

Integrating with Contact APIs in PHP

So for the last week and change I’ve been working with the various contact API’s of 4 of the major email providers.

Google has been the easiest to work with, but it is also one of the least secure. It’s built on their Gdata platform, so you know it’s very well documented. It’s only downfall is that it does not require the user to enter their login information through google. This leaves it wide open for spammers to create phishing scams. Be cautious when a site asks you to invite your google contacts. If it’s not a website that you 100% trust, such as facebook or myspace, it might be best just to enter your contacts manually. You can check out the Google Contacts Data API here.

Yahoo implements a handshake-style authentication protocol, which is pretty smooth and will hopefully leave the user feeling more secure with their personal information. It requires the user to login through Yahoo and then Yahoo passes an authentication token back to your application. There’s still the potential for phishing scams, you be sure that you check your location bar and see yahoo.com (or .ca, .co.uk, etc) in the top-level domain. The Yahoo API is well documented and quite simple to use. It’s probably my favorite implementation. You can check out the Yahoo! Address Book API here.

Hotmail also implements a handshake-style authentication protocol. However, the documentation is poor and quite confusing. I think I spent more time following links in the MSDN than actually coding. Microsoft also offers an SDK which, though poorly documented and slightly confusing, I would not have been able to get by without. You can check out the Windows Live Contacts API here.

AOL is the worst of the 4. They’re so behind the times that they still haven’t even released a contacts API. If you want to allow your users to import their AOL contacts, you’ll have to sink down to the level of screen scraping. Hopefully you’ll be able to check out the AOL Address Book Open Services here some day soon!

I’m actually surprised that no one has implemented integration with these contact API’s for the Zend Framework yet, seeing as how much of a sought after commodity they are in these days of social networking sites. I guess now all that’s left for me to do is to clean up some of the code and write a couple of Zend Framework proposals!

October 6, 2008 at 6:13 am 2 comments

Oh CRUD…

My article “Oh CRUD…” was just published in the July 2008 issue of php|architect magazine. Check it out here: http://phparch.com/c/magazine/issue/78

August 4, 2008 at 9:18 pm Leave a comment

Favour Composition over Inheritance

I was just reading through the current issue of php|architect ( April 2008 ) and I noticed a particular piece of code that irked me to the point that I need to write about it. If you’re interested, the article is Exceptional Error Handling. Don’t get me wrong, it’s a well written and informative article, however, one of the listings (Listing 9) has some really hacky code in it. The hack is only in the constructor, but the flaw is in the design. A flaw that can easily be overcome with a piece of sage advice from the Gang of Four: “Favour object composition over class inheritance” [GoF20]

The intention of the code is to have a singleton class that extends PHP’s ArrayObject class. Here’s the code snippet:

class LogService extends ArrayObject
{

    private static $instance;

    public function __construct(Array $loggers = array())
    {
        // examine backtrace to see how the constructor was called
        $backtrace = debug_backtrace();

        // throw exception if we were not called from the
        // getInstance() method of this class
        if ($backtrace[1]['class'] != __CLASS__ ||
            $backtrace[1]['function'] != 'getInstance'){
            throw new SingletonException('...');
        }

        parent::__construct($loggers);
    }

    public function getInstance(Array $loggers = array())
    {
        if (!self::$instance){
            self::$instance = new LogService($loggers);
        }
        return self::$instance;
    }

    ...
}

NB: i left out the rest of the class and the content of
the exception message because it's not really relevant
to the point at hand.

Can you spot the problem here?

The problem is that this breaks one of the main rules of the singleton pattern — that new instance of the class cannot be created from outside of the class — and then attempts to reconcile it by checking the backtrace and throwing an exception. Since the constructor of the ArrayObject class is defined as public, any child classes of ArrayObject must also have their constructor defined as public. This is because access to a method of a child class cannot be more restrictive than that method in the parent class. The final solution ended up being a hacky mimic of the singleton pattern.

Ockham’s razor (or at least a paraphrased version): “the simplest solution is the best”

Checking the backtrace and throwing an exception is not the simplest solution. The simplest solution is to favour composition over inheritance.

Let’s look a little deeper at the ArrayObject class

ArrayObject

You’ll see that the ArrayObject implements 3 interfaces: IteratorAggregate, ArrayAccess, and Countable. These interfaces are what allow php to treat instances of the ArrayObject as native array, i.e. using it in a foreach loop, accessing elements of the ArrayObject, finding out how many elements are in the ArrayObject, etc.

Let’s see how we can use composition and interfaces to write an equivalent singleton class without the need for the hacky constructor


class LogService implements IteratorAggregate, ArrayAccess, Countable
{

    // the only available instance of this class
    private static $_instance;

    // an instance of ArrayObject. using composition rather than
    // inheritance
    private $_array;

    // private constructor as an optimal solution for the singleton
    // pattern
    private function __construct(Array $loggers = array())
    {
        $this->_array = new ArrayObject($loggers);
    }

    // method required by the IteratorAggregate interface
    public function getIterator()
    {
        return $this->_array->getIterator();
    }

    // method require by the ArrayAccess interface
    public function offsetExists($index)
    {
        return $this->_array->offsetExists($index);
    }

    // method require by the ArrayAccess interface
    public function offsetGet($index)
    {
        return $this->_array->offsetGet($index);
    }

    // method require by the ArrayAccess interface
    public function offsetSet($index, $newval)
    {
        return $this->_array->offsetSet($index, $newval);
    }

    // method require by the ArrayAccess interface
    public function offsetUnset($index)
    {
        return $this->_array->offsetUnset($index);
    }

    // method required by the Countable interface
    public function Count()
    {
        return $this->_array->count();
    }

    public function getInstance(Array $loggers = array())
    {
        if (!self::$_instance){
            self::$_instance = new LogService($loggers);
        }
        return self::$_instance;
    }

    ....

}

In my opinion this is a much more elegant solution, even if it does require a little bit more coding (and very trivial code at that). There’s no way to call the constructor outside of the class and thus no need to manage the possibility of an exception thrown by the constructor. It serves the same purpose as the original code (you could even implement the php’s magic method __call() in the LogService class to essentially proxy method calls to the instance of the ArrayObject) and is more inline with the intention of the Singleton pattern.

What do you think? Which solution would you prefer? What do you think is more important: good design practices or less lines of code?

June 4, 2008 at 12:52 pm Leave a comment

Propel: BaseObject Collection

Here the code snippet I promised in my last blog entry. Two very simple pieces of code — 1 class and 1 interface — that use the existing PHP array functionality with an OO face-lift. Since Propel methods such as doSelect() return a regular PHP array, all you need to do is pass that array to the constructor of the BaseObjectCollection in order to have an OO interface to your Propel collections. the BaseObjectCollection can (and should) be extended to allow for a type-hinted add method and allow for additional methods that are collection specific.

The first piece of code required is the interface:

interface BaseObjectCollectionInterface extends IteratorAggregate
{
	public function add(BaseObject $o);
	public function addAll(BaseObjectCollectionInterface $c);
	public function clear();
	public function contains(BaseObject $o);
	public function containsAll(BaseObjectCollectionInterface $c);
	public function indexOf(BaseObject $o);
	public function isEmpty();
	public function remove(BaseObject $o);
	public function removeAll(BaseObjectCollectionInterface $c);
	public function size();
	public function toArray();
}

You’ll see that this extends PHP’s native IteratorAggregate interface which will allow the collection to have an iterator traversed in foreach loops and other related functionality. This interface is also loosely based on the Java API Collection interface. It defines the minimum functionality that is expected of a BaseObjectCollection.

The next piece of code is the actual Collection class:

class BaseObjectCollection extends ArrayObject implements BaseObjectCollectionInterface
{

	public function __construct(array $array = array())
	{
		parent::__construct($array);
	}

	public function add(BaseObject $object)
	{
		$this->append($object);
	}

	public function addAll(BaseObjectCollectionInterface $collection)
	{

		foreach($collection as $element){
			$this->add($element);
		}

	}

	public function clear()
	{
		$this->exchangeArray(array());
	}

	public function contains(BaseObject $object)
	{
		return (boolean)in_array($object, (array)$this, true);
	}

	public function containsAll(BaseObjectCollectionInterface $collection)
	{

		$containsAll = true;

		foreach($collection as $element){

			$containsAll = $containsAll && $this->contains($element);

			if (!$containsAll){
				return false;
			}

		}

		return true;

	}

	public function indexOf(BaseObject $object)
	{
		return array_search($object, (array)$this, true);
	}

	public function isEmpty()
	{
		return ((int)$this->count() == 0);
	}

	public function remove(BaseObject $object)
	{

		$index = $this->indexOf($object);

		if ($index !== false){
			$array = (array)$this;
			array_splice($array, $index, 1);
			$this->exchangeArray($array);
			return true;
		}

		return false;

	}

	public function removeAll(BaseObjectCollectionInterface $collection)
	{

		foreach($collection as $element){
			$this->remove($element);
		}

	}

	public function size()
	{
		return $this->count();
	}

	public function toArray()
	{
		return (array)$this;
	}

}

You should notice that this collection implements the BaseObjectCollectionInterface defined previously as well as extends the PHP ArrayObject class. The majority of the functionality required for this collection is implemented in the ArrayObject class, and by extending this class the BaseObjectCollection can utilize much the built in PHP functionality such as ArrayAccess and can be passed to PHP array functions such as count().

The code itself is quite simple. But then again, in most cases the simplest solution is the best.

May 28, 2008 at 11:33 pm Leave a comment

PHP Object/Relational Mapper

In the past I used to write my own object relational mapping tools. This was time consuming and cumbersome but it afforded me the maximum amount of freedom to implement my domain model designs exactly as I envisioned them. However, as project deadlines began to get shorter and shorter, I just didn’t have the time to devote to writing a custom object model for each project — no matter how much the project needed it. Luckily a colleague of mine turned me on to Propel, an open source tool that will generate a rich object model. All you need to do is create an XML file based on your database and Propel’s runtime generator will generate an object model that maps nicely to your database. In a matter of minutes (or for a really complex project, hours) I can have a fully functional, bug free, object model to begin working with.

As if that wasn’t good enough, Propel also contains a class called Criteria. This class is used as an OO API for writting SQL queries — from simple to increasingly complex. This is something that I’ve always meant to write for myself but just never had the time to do it right. The Criteria class is quite effective and easy to use once you get comfortable with it. Unfortunately the Propel API documentation isn’t the greatest and like me, you’ll probably spend a while reading through the code. That is if you want more than a peripheral understanding of the Criteria class.

The only downside about Propel is that in a lot of ways it’s missing functionality that I was able to write into my custom object model. Since I don’t have access to editing the base Propel classes, any functionality that I want to apply to the entire domain model has to be hard coded into each class. This can become pretty cumbersome and isn’t very reusable among different projects. Luckily Propel is open-source, so the solution here is to become involved in the Propel community and attempt to offer my suggested extensions and offer my help in future development.

My biggest problem with Propel right now, is that collections of objects are returned as an array. I’m surprised that an ORM tool would not have a collection class that allows an OO interface for dealing with an manipulating collections of objects. Especially since the SPL has a great set of classes for implementing iterators and various collections. One of the main Propel extensions that I’ve been using for my projects has been a class that models a collection of objects. It extends the SPL ArrayObject class and implements an interface based on the Java.util.Collection interface.

I’ll post a little code snippet shortly…

May 20, 2008 at 4:36 am Leave a comment

First article down!

So I recently finished my first article for php|architect magazine. I really don’t think I would have gotten through it without rockstar engery drinks. I wonder if they’ve ever thought about sponsoring a programmer… haha. Energy drinks are to programmers as gatorade is to professional athletes. I guess programmers aren’t as high profile. We’ll see what the future holds!

My article is on encapsulating CRUD processes for reusability and portability. I’m pretty happy with how it came it. I finished it off at about 3800 words, but we’ll so what the editing process does to it. Overall it was a good experience. I’d really like to continue writing programming articles. I hope that the article goes over well. I’ll post a link to it once it’s published.

In the last little while I’ve been working a lot with Facebook’s API for PHP. I really don’t like the PHP API client that they offer. It doesn’t give very helpful error messages, which lead me to tons of frustration. It also just seems like an OO wrapper written by someone who was trained in procedural programming. It just doesn’t sit right with me. I might just have to try my hand at my own PHP client for the Facebook API.

March 31, 2008 at 1:40 am Leave a comment

Hello World!

You might think that the ironic thing here is that someone such as myself – who is looking to show off their skills as a programmer – is using a third party solution. But hey, why reinvent the wheel? And I get to support open source technologies written in PHP. It’s win-win. Not mention blogs have been done to death. I’d rather spend my time working on more interesting projects and leave the blog programming to word press. Glad that’s out in the open.

I’m setting up this site set to blog about PHP and other relevant nerdery, showcase many of the awesome projects that I’ve had the opportunity to work on, and be a home for my CV. Hopefully I’ll have a fair amount of real content posted in the next couple weeks.

For now, I’m keeping busy working on my first article for php|architect magazine, (if you haven’t been reading it religiously for the last couple years, you’re really missing out), writing extensions for the Zend Framework, and getting my feet wet transitioning from developing RPC-style to RESTful web services.

The excitement just never seems to end.

throw new Exception(“I’m not as nerdy as this post makes me appear!”);

February 20, 2008 at 3:10 am Leave a comment


Categories

  • Links

  • Feeds


    Follow

    Get every new post delivered to your Inbox.