PHP 5.3 namespaces for the rest of us

Accord­ing to the offi­cial doc­u­men­ta­tion, PHP name­spaces have been designed to pre­vent name col­li­sions between classes from dif­fer­ent pack­ages and to avoid the use of very long names in the code to refer to classes or functions—nobody really wants to have to deal with some­thing called Zend_Db_Adapter_Mysqli or PHPUnit_Framework_Constraint_IsInstanceOf, after all. This means that name­spaces help a devel­oper write code that is both more con­cise and clearer—a direc­tion which is always an improve­ment towards expressiveness.

Within the PHP imple­men­ta­tion of name­spaces, these names will be ide­ally refac­tored to Zend\Db\Adapter\Mysqli and PHPUnit\Framework\Constraint\IsInstanceOf, where \ is the name­space sep­a­ra­tor. In the code­base, how­ever, there will typ­i­cally be very few ref­er­ences to these classes with their fully qual­i­fied name, because it is pos­si­ble to import entire name­spaces in a script and then use the class names directly, mak­ing the code eas­ier to fol­low and unam­bigu­ous to write.

In fact, the def­i­n­i­tion of a name­space class itself does not con­tain its fully qual­i­fied name. For exam­ple, this would be the source file of an hypo­theth­i­cal MyLibrary\TypeOfComponents\MyClass class:


namespace MyLibrary\TypeOfComponents;

class MyClass
{
// …
}

The con­ven­tion when writ­ing namespace-enabled code is that of cre­at­ing a folder struc­ture that reflects the indi­vid­ual com­po­nents of a name­space (for exam­ple, MyClass would be in the MyLibrary/TypeOfComponents direc­tory. This helps stan­dard­iz­ing the autoload­ing process.

Read the full story PHP 5.3 name­spaces for the rest of us | php|architect.

Tags: , ,

Leave a Comment

*

Get Adobe Flash playerPlugin by wpburn.com wordpress themes