Talks around PHP, Computer Science and Stuffs
In: PHP
17 May 2009Some people just like to write as few line of codes as possible. Well, PHP can be tricky sometimes.. For instance, be carefull when declaring a variable and passing it as a parameter to a function or to a method at the same time. If that parameter is supposed to be passed by reference, you may end up with some unexpected behaviors !
Look at the following code, What do you think will be outputted ?
function changeStr(&$str)
{
$str = 'foo_' . $str;
return $str;
}
$res = changeStr($str = 'bar');
var_dump($str);
var_dump($res);
Here is the result.
string 'bar' (length=3) string 'foo_bar' (length=7)
So basically, $str hasn’t been affected by the changeStr() function. Let’s try with an array now..
function changeArr(&$arr) { $arr['id'] = 10; return $arr; } $res = changeArr($arr = array()); var_dump($arr['id']); var_dump($res['id']);
The result is…
null int 10
Well, same behavior as earlier. $arr wasn’t altered by the changeArr() function !
What about objects, does it do the same thing ?
function changeObj(&$obj) { $obj->id = 10; return $obj; } $res = changeObj($obj = new StdClass()); var_dump($obj->id); var_dump($res->id);
Here is the result.
int 10 int 10
So, it doesn’t work for a string or an array, but it work with objects !
Well, I highly suggest any developer not to declare a variable and pass it to a method or a function at the same time. Just write the additional line of code, it is gonna reduce the risk of error and actually might make your core more readable !
In: Design Pattern| PHP| Singleton
17 May 2009I have decided to write a serie of posts around the Singleton design pattern. This first one will discuss the uniqueness aspect of a Singleton.
What is a Singleton again ?
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. (Wikipedia)
Here is a typical implementation of a Singleton class in PHP. You will see this kind of code in many different existing frameworks.
/**
* A typical implementation of a Singleton
*/
class aSingleton
{
private static $_instance = null;
public $foo = null;
private function __construct()
{
}
public static function getInstance()
{
if(null === self::$_instance)
{
self::$_instance = new aSingleton();
}
return self::$_instance;
}
}
So, is there anything wrong with that code ?
One of the things that I really dislike about this implementation (there are actually many others things I dislike about Singleton, but I will discuss them in others posts), is the fact you cannot (actually this isnt necessarily true as we will see later) have two different instances of a Singleton. I dont understand why a class should enforce a such rule / constraint. Why would someone want to have a such constraint ? What good would it make ?
Some may argue that sometimes in an application, you want to keep using the same instance of an object. Usually, they will say that objects like a logger, a configuration or a database handler are good candidates for a such use. Well, that’s fine with me, but why do I have to use a Singleton for that ? Is this really the best solution to do that ?
Let’s use a parrallel. Imagine, we need to always use the same hammer to do a job for some good reason. So, we decide you are going to enforce that requirement, by destroying all the others existing hammers and any shop / factory selling or producing hammers. That way, when we use a hammer, we are sure it is the same one (it is the only hammer that exist in the whole universe and it is impossible that for any other hammer to get built).
Doesn’t that sound crazy and extreme ? I mean, why wouldn’t we just mark that hammer (write a name on it or something) and just store it in a specific place, so we know where to get it and we can ensure that we are using the same hammer. Also, if one day we do need to have another hammer, well we would be able to…
There is also a problem with most existing implementations of a Singleton. The design pattern is supposed to enforce the number of different instance of a particular class, right ? Well, there are ways to bypass that and end up with different instances of a Singleton.
In PHP, we could use the clone construct.
$a = aSingleton::getInstance();
$a->foo = 10;
$b = clone $a;
$b->foo = 20;
echo $a->foo . PHP_EOL; // Display 10
echo $b->foo . PHP_EOL; // Display 20.
// Damn this isnt anymore my Singleton!
To prevent that, we would need to implement the __clone() method (define it as final and throw some kind of exception whenever called). This would solve the issue with the clone construct.
Well, that still won’t completely prevent someone from being able to have two different instances of our Singleton. Someone could still use the serialization. Look at this code.
$a = aSingleton::getInstance();
$a->foo = 10;
$str = serialize($a);
$b = unserialize($str);
$b->foo = 20;
echo $a->foo . PHP_EOL; // Display 10
echo $b->foo . PHP_EOL; // Display 20.
// Damn this isnt anymore my Singleton!
Again, to prevent that, we could implement the __wakeup() method (also declare it as final and throw some kind of exception).
So, we just added a new constraint on the class : We cannot unserialize it anymore via the unserialize function. If we cannot unserialize, then we made serialization pretty much useless…
That’s the end of this first post on Singleton. I am hoping that after reading this, you already feel (if you are a Singleton adept) that there might be something wrong or bad using this design pattern.
My next post will discuss other aspects that I really dislike about Singleton, such as how to unit test Singleton, why Singleton is a global state and why global states are bad, etc.
A few weeks ago, I made a post about a very interesting video made by Miško Hevery intituled “The Clean Code Talks - Don’t Look For Things!”.
Today, I discovered that there is a PDF summarizing the important principles, with actually some very detailled examples also.
I really highly suggest to any programmer interested by unit testing to take the time to read this document.
It can be found on Miško Hevery’s website or you can directly download the pdf from this shortcut.
Here is a summary of the content of that pdf (this is taken directly from Miško Hevery’s website).
Flaw #1: Constructor does Real Work
Warning Signs
- new keyword in a constructor or at field declaration
- Static method calls in a constructor or at field declaration
- Anything more than field assignment in constructors
- Object not fully initialized after the constructor finishes (watch out for initialize methods)
- Control flow (conditional or looping logic) in a constructor
- Code does complex object graph construction inside a constructor rather than using a factory or builder
- Adding or using an initialization block
Flaw #2: Digging into CollaboratorsWarning Signs
- Objects are passed in but never used directly (only used to get access to other objects)
- Law of Demeter violation: method call chain walks an object graph with more than one dot (.)
- Suspicious names: context, environment, principal, container, or manager
Flaw #3: Brittle Global State & SingletonsWarning Signs
- Adding or using singletons
- Adding or using static fields or static methods
- Adding or using static initialization blocks
- Adding or using registries
- Adding or using service locators
Flaw #4: Class Does Too MuchWarning Signs
- Summing up what the class does includes the word “and”
- Class would be challenging for new team members to read and quickly “get it”
- Class has fields that are only used in some methods
- Class has static methods that only operate on parameters
A friend and I have been working on different projects together. We recently decided to share one of our script to the open source community.
The name of the tool is the Autoload Manager.
The AutoLoad Manager is a generic autoloader that can be used with any PHP framework or library. Using the PHP tokenizer mechanism, it will parse folder(s) and discover the different classes and interfaces defined. The big advantage of using this autoloadManager is that it will allow you to implement whatever naming rules you want and may have mutliple classes in one file (if you want to have a such feature).
So basically, you don’t have anymore to implement some complex naming rules between the filename and the classname. You may organize the way you want your API (may have as many subfolders as you want, you may have multiple API folders, etc.).
Would you like to know more about it ? Then, check the documentation here.
Wufoo shares a very neato tool called PHP Quick Profiler or PQP. It basically allows a developper to have some usefull and fancy logging on a piece of code.

How hard is it to use ?
Well, it took me around 3 minutes to download and use it on one of my scripts.
Here is what I got on a custom test script. Doesn’t that look nice ?

Wanna try it ? You can find all info here:
http://particletree.com/features/php-quick-profiler/
In: PHP Framework
28 Apr 2009YII is a PHP framework, with a lot of goodies such as :
As any other good framework, it comes with a bunch of tools, scripts to auto-generate skeleton code or classes.
I have watched the screencast, and it seems fairly good. I have added YII to my list of things to test. Expect soon a post about YII
Meanwhile, you can check out YII @ http://www.yiiframework.com/
In: PHP| Singleton| Unit Testing
21 Mar 2009I recently watched an interesting presentation from Miško Hevery intituled “The Clean Code Talks - Don’t Look For Things!”. This presentation discusses some best practices to follow in order to keep a code clean. It talks about unit testing and the law of Demeter in OOD.
For the people who never heard about it, the law of Demeter can be succinctly summarized as “Only talk to your immediate friends.” The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).
The construction of an object should be easy
In his presentation, Miško emphasizes on the importance to make it easy to construct an object. The easiest the construction of an object is, the easier it is to test it.
Let’s look at the following code.
<?php
class Document
{
public $html;
public function __construct($url)
{
$client = new htmlClient();
$this->html = $client->get($url);
}
}
The instantiation of a Document object relies on the call to the “get” method of the htmlClient. Testing that class would rely on the htmlClient class and the previous code don’t allow to use any form of mockup object.
What about the following code ? Wouldn’t it be easier to test ?
<?php
class Document
{
public $html;
public function __construct($html)
{
$this->html = $html;
}
}
This code would be much easier to test, this is mainly due to the fact that the instantiation is lighter and easier to perform.
A practical example
Imagine you are in a store and the item you are purchasing is 25$.
The answer seems pretty obvious. Let’s see now how this could be interpreted in PHP.
<?php
class Goods
{
public $accountReceivable;
public function __construct($config)
{
// Instantiating the accountReceivable
// using the config
$ar = new accountReceivable($config);
$this->accountReceivable = $ar;
}
public function purchase(Customer $customer)
{
$wallet = $customer->getWallet();
$money = $wallet->getMoney();
$this->accountReceivable->recordSale($money);
}
}
Lets look at the constructor method. It receives a config parameter that will be used to instantiate the accountReceivable object and then assign it to the property of the goods class.
The purchase method receives a customer object. It will retrieve the wallet and the money. Then, it will call the recordSale method and pass the money as a parameter.
So, Why is the previous code sample a bad implementation ?
First, it violates the “law of Demeter” principle by calling getMoney on the wallet ($customer->getWallet()->getMoney()). This makes objects more dependent on the internal structure of other objects.
Second, this code is hard to unit-test and will require instantiating objects such as the config and customer when being tested, as you can see in the following code.
<?php
class GoodsTest
{
public function testPurchase()
{
// Make it harder to create a mockup object
$config = new config($fileName);
$goods = new Goods($config);
$customer = new customer(new Money(25, "USD"));
$goods->purchase($customer);
assertEqual($this->accountReceivable, 25);
}
}
So, how can we improve this code ? Let’s look at the following code.
<?php
class Goods
{
public $accountReceivable;
public function __construct(accountReceivable $ar)
{
$this->accountReceivable = $ar;
}
public function purchase(Money $money)
{
$this->accountsReceivable->recordSale($money);
}
}
Why is this code better for unit testing ? First, the constructor don’t rely anymore on the config object. The accountReceivable object is passed directly into the constructor. We will be able to use a mockup object for accountReceivable.
Secondly, the purchase method now receives a money object, instead of the customer. It receives exactly what it needs in order to perform a purchase. We don’t rely anymore on the getWallet() and getMoney() methods.
Our testing class could look like this.
<?php
class GoodsTest
{
public function testPurchase()
{
// Using a mockup object
$ar = new accountReceivableMockUp();
$goods = new Goods($ar);
$goods->purchase(new Money(25, "USD"));
assertEqual($this->accountReceivable, 25);
}
}
Use of pre-conditions inside a constructor
Another concerns raised Miško with unit-testing is the use of pre-condition inside constructors. Let’s look at the following code.
<?php
class House
{
public function __construct($window)
{
if(null === $window)
{
throw new Exception();
}
}
}
How the previous could make unit testing harder ? Let’s assume that there is a paint method that receives a color as a parameter. The test of that single method would actually require to pass a not null parameter into the house constructor. So, it wouldnt be possible to do the following.
<?php
$house = new house(null);
$house->paint("red");
Singleton and unit-testing
The use of singleton can potentially make unit testing harder. Let’s assume we have a printer class that implements a method named print. If the passed parameter is null, we would like to log a message.
<?php
class printer{
public function print($document = null)
{
if(null === $document)
{
// Retrieve Singleton logger
$logger = logger::getInstance();
$logger->logMessage("Print Error!");
}
// ...
}
}
The print method will be hard to unit-test since it uses the logger singleton object. The unit test is no longer contained within known boundary conditions and may generate false results. Also, in the previous code, there is no easy way to substitute a mock object for the logger in a unit test to establish a known boundary condition.To overcome that problem, dependency injection can be used. The following code is an example.
<?php
class printer{
public function print($document = null, $logger)
{
if(null === $document)
{
$logger->logMessage("Print Error!");
}
// ...
}
}
In: PHP| Programming language
20 Mar 2009One of the characteristic of PHP is that it doesn’t do strong typing.
PHP 5.1 introduced Type Hinting. Functions were able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays.
I recently read one RFC (Request For Comments) - on PHP.net wiki - from Felipe Peruna about Return value and parameter type hint. Basically, the idea is to allow to specify what will be the type of the result of a function or method. Here is an example.
<?php
class test {
public function (int) foo(){
// ...
}
}
In that previous example, the method foo must return an integer, if that’s not the case, then the following error will be triggered : “Catchable fatal error: The returned value must be of the type integer”.
I personally think this could come handy in some cases.
In: Design Pattern| MVC
18 Mar 2009I read an interesting post on Domain Driven Design on Fede.carg’s blog. Ever heard about Domain Driven Design ?
Domain-driven design separates the model layer “M” of MVC into an application, domain and infrastructure layer. The infrastructure layer is used to retrieve and store data. The domain layer is where the business knowledge or expertise is. The application layer is responsible for coordinating the infrastructure and domain layers to make a useful application. Typically, it would use the infrastructure to obtain the data, consult the domain to see what should be done, and then use the infrastructure again to achieve the results.
In: PHP| Programming language
18 Mar 2009I had the chance to attend the PHP Québec Conference this year. It was very interesting. I highly encourage anyone to attend such conferences if he / she is interested by PHP.
Anyway during one of the presentation, I discovered an interesting little script / tool named PHPLoc. It is written by Sebastian Bergmann and It will basically parse php files (of a project for intstance) and return some informations related to its size.
Here is an example directly taken from github.com :
sb@ubuntu ~ % phploc /usr/local/src/ezcomponents/trunk/Workflow
phploc 1.1.0 by Sebastian Bergmann.Directories: 13
Files: 102Lines of Code (LOC): 14066
Executable Lines of Code (ELOC): 5710
Comment Lines of Code (CLOC): 5228
Non-Comment Lines of Code (NCLOC): 8838Interfaces: 7
Classes: 90
Functions/Methods: 566
My name is Bashar Al-Fallouji, I am an IT Consultant and Co-Founder at DevMotion.
I am particularly interested in Web applications, Open Source Development, Software Engineering, Information Architecture, Unit Testing, XP/Agile development, etc.
On this blog, you will find mostly technical articles and thoughts around PHP, OOP, OOD, Unit Testing, etc. I am also sharing a few open source tools and scripts.