Friday, 22 February 2013

PHP namespace conventions

With the advent of namespaces in PHP, code is thankfully getting much less complicated by reducing the somewhat messy class naming (though namespacing does affect more than just classes).

As a developer, and stepping into the world of PHP namespacing for the first time, I began to start asking myself about standards and conventions. Many of PHP's features can be interpreted in a number of different ways and namespacing is no different, so a standard would be really helpful, especially in larger projects.

Luckily, a PHP Standards Working Group have put forward a proposal that makes geat sense as a standard to work to. This standard also allows for easily autoloader support which I was also after.

Here's the basic rules:
  • A fully-qualified namespace and class must have the following structure:
    • \<Vendor Name>\(<Namespace>\)*<Class Name>
  • Each namespace must have a top-level namespace ("Vendor Name").
  • Each namespace can have as many sub-namespaces as it wishes.
  • Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.
  • Each _ character in the CLASS NAME is converted to a DIRECTORY_SEPARATOR. The _ character has no special meaning in the namespace.
  • The fully-qualified namespace and class is suffixed with .php when loading from the file system.
  • Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.

More information on the proposed format know as PSR-0 can be found here:

No comments:

Post a Comment