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.

PHP Quick Profiler

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 ?

QPQ Example
 
Wanna try it ? You can find all info here: 
http://particletree.com/features/php-quick-profiler/

YII is a PHP framework, with a lot of goodies such as :

  • MVC
  • Multiple DB
  • ORM
  • DB Objects
  • Templates
  • Caching
  • Validation
  • Ajax
  • Auth Module

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/

I 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$.

  • Do you give the clerk your wallet and let him/her retrieve the 25$ ?
  • Or, do you give the clerk 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!");
        }

        // ...
    }
}

One 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.

I 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.

I 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: 102

Lines of Code (LOC): 14066
Executable Lines of Code (ELOC): 5710
Comment Lines of Code (CLOC): 5228
Non-Comment Lines of Code (NCLOC): 8838

Interfaces: 7
Classes: 90
Functions/Methods: 566

You are using some CMS but don’t really like the way it handles URL’s … ?

For example, instead of having “www.mysite.com/index.php?id=12”, you would like to have “www.mysite.com/love” ?

Well, MOD_SQLAlias may be the solution for you, it is an Apache2 module under LGPL, it “will intercept specific URI requests and dispatch them to the appropriate page to be served using a MySQL alias table“.

Basically, you can install this apache module and use it with your current website. It will be completly transparent and will work with your current CMS.

The project can be found on sourceforge here: Mod_SqlAlias on sourceforge

Ever wondered what is the fastest programming language ? Here you will find some benchmarks. Have fun comparing the results.

Languages benchmark

Well, guess in what position is PHP ?

Code contest graph

Thank god Ruby is here…

Code contest summary

This website should add some “energy” to the never ending debate “What is the best programming language”… 😉

There are many posts about what editor to use when programming with PHP.

I have been using VIM since about 7 months, I got convinced by a fellow coworker to use it. I gotta admit, it was a headache at the beginning, but the more I use it, the more I like it.

If you ever want to try using VIM with PHP. Here is an excellent presentation on how to use VIM & PHP on Andrei Zmievsky’s website.

You can also download his .vimrc (VIM config file) and plugins files here: Download Andrei’s VIM files

So.. I finally decided to start my own Blog.

Why? Well, like many fellows, I do spent time to read about “stuffs” on the web and I felt it was time to share some of my findings.

What do I read about usually ? Actually, kinda anything…

Ok, I will start with a framework that I just discovered, it is named “Not One Line Of Html”… I like the name but I am not sure I would use a such framework, I find it too extreme in my humble opinion. However, if you are as curious as I am, go take a look and make yourself your own opinion .

It is a PHP framework that wraps lot of HTML components in PHP.

Look at the following code, it will basically show up a button. When you click on the button, it will change the text of the button.

NOLOH Code

You can check out their tutorial video on : http://www.noloh.com

Who am I?

My name is Bashar Al-Fallouji, I work as a Enterprise Solutions Architect at Amazon Web Services.

I am particularly interested in Cloud Computing, Web applications, Open Source Development, Software Engineering, Information Architecture, Unit Testing, XP/Agile development.

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.

  • Trinzia: Well done, my friend! [...]
  • vivek raj: Hello Bashar, It's really good that you wrote this code. but I'm confused some part. can you suppor [...]
  • irfan: I saw watch your youtube talk on clean and testable code. By the way very good talk. I was wondering [...]
  • Mohamed: Hello bashar, I hope you are doing well. Thank you for your hard work, and thank you for sharing [...]
  • alex davila: Hi Bashar is there any pick up example?? Regards Alex Davila [...]