Create better namespaces in PHP

Tips for creating more intuitive namespaces

PHP V5.3 introduces the ability to provide namespaces to your PHP classes, constants, and functions. Using namespaces allows you to avoid naming collisions and provide context for your PHP code. These tips provide a few guidelines for building your namespaces so that you get the most out of them.

Share:

Nathan A. Good, Senior Information Engineer, Freelance Developer

Nathan GoodNathan A. Good lives in the Twin Cities area of Minnesota. Professionally, he does software development, software architecture, and systems administration. When he's not writing software, he enjoys building PCs and servers, reading about and working with new technologies, and trying to get his friends to make the move to open source software. He's written and co-written many books and articles, including Professional Red Hat Enterprise Linux 3, Regular Expression Recipes: A Problem-Solution Approach, and Foundations of PEAR: Rapid PHP Development.



23 June 2009

Also available in Japanese Portuguese

Namespaces — introduced in PHP V5.3 — are a way of giving your PHP classes, constants, and functions context so that elements with the same names can be understood as being unique. The unique names allow you to avoid naming collisions, which occur when two classes or functions of the same name exist. Sometimes, those PHP classes represent the same objects in your physical domain, but the behavior of the class is entirely different. Namespaces are a way of making sure you have the correct PHP class, constant, or function and that people using your PHP classes can be sure they're using the correct ones.

Namespaces in code work just like contexts in the physical world. Consider a class that represents the real-world domain object automobile. To a company that sells automobiles over the Internet, the Automobile class may have entirely different behaviors from the Automobile class a company that sells insurance uses.

As an application developer, you might use components written by other people. You can never be sure that those people didn't decide to use the same class names you have, but for an entirely different class. Before namespaces, it was typical for a PHP developer to build the context into the name of the class, like My_Enterprise_Person or XML_Validator.

Listing 1 shows an example of a class that resides in a namespace.

Listing 1. Declaring a class in a namespace
<?php
namespace IBM;
class Foo {
...
}
?>

An example of referring to a class in a namespace is shown below.

Listing 2. Referring to a class in a namespace
<?php
$foo = new \IBM\Foo();
?>

Defining a namespace policy is a good idea before you start adding namespaces to all your classes. Although it is acceptable to a certain extent to grow your namespaces by building them over time, it is better to decide a common structure for your namespaces that makes it easier to organize them and reduce the chance of a lot of rework later. When used correctly, namespaces can be a method for organizing your PHP code in addition to providing context.

Other languages, like the Java™ and C# languages, have had namespaces for a long time. In choosing how to name my namespaces, I use conventions similar to those languages because they're familiar and understood by many developers. However, unlike the Java language, the namespaces in PHP are not linked to the directory in which the class resides. You can give a class, function, or constant any namespace you choose. You can even use more than one namespace per file. And unlike C#, you can give namespaces to functions or constants that aren't inside classes.

High-level namespaces

If you are building applications for an organization, use your organization name as a high-level domain. Creating a high-level namespace with your organization name is usually enough to give your PHP code context and avoid naming collisions, unless your organization writes many applications for different purposes or for subdivisions.

Listing 3 contains an example of declaring a high-level namespace.

Listing 3. A high-level namespace
<?php
namespace IBM;
...
?>

Subnamespaces

Subnamespaces are namespaces inside high-level namespaces. They provide further clarification if the high-level namespace isn't enough to establish context for the PHP class you're creating.

When creating subnamespaces, it's important not to become overzealous and create too many. They become difficult to organize and reference later if they become too numerous. This is particularly important when you're using namespaces for the purpose of organizing your PHP code, as well as avoiding naming collisions.

When deciding how many subnamespaces to introduce into another namespace for organizational purposes, I try to keep the number limited to seven (plus or minus two) in order to take advantage of the idea that, conceptually, chunks of seven items are easier to remember. This doesn't always work, but I use it as a guideline to determine whether I'm carving up namespaces into too many subnamespaces.

Listing 4 shows an example of declaring a subnamespace inside a high-level namespace.

Listing 4. A subnamespace
<?php
namespace IBM\DeveloperWorks;
...
?>

The subnamespace ("DeveloperWorks") is separated from the high-level namespace ("IBM") that contains it with the backslash (\) character.

When you're declaring subnamespaces, you can use a couple of common techniques or a combination thereof. One common place to get names for subnamespaces is from project or application names; the other is from the domain name.

Defining by project

If you've used your organization name as the high-level namespace and still seek subnamespaces to further provide context, you can use project or application names as the name of a subnamespace. For instance, if you are building a new application called Greeter that asks for users' names and greets them, use a namespace like the one in Listing 5 to give full context to a class called Prompt.

Listing 5. Using the application name as a subnamespace
<?php
namespace IBM\Greeter;
class Prompt {
...
}
?>

Because Prompt could be the name of a class in several applications or libraries, providing this namespace with the organization name and project name sets this Prompt apart from the others.

Defining by domain

Using the name of a domain is another common scheme for choosing subnamespace names, as Listing 6 shows. It may or may not be used in addition to the project name, depending on your plans for reusability (see "Naming for reusability").

A domain is a group or classification of things found in the larger problem domain. An example of a domain can be "Account," "Customers," or "Products" in a larger application that deals with accounts, customers, and products.

Listing 6. Using the domain as a subnamespace
<?php
namespace IBM\MyApp\Account;
class Address {
...
}
?>

Naming for reusability

In addition to applying concepts of modularity that enable reusability, the way you name classes and namespaces gives them an implied purpose and, therefore, reusability. Sometimes, poor naming choices hinder reusability because the poor names imply that a class is limited to a specific purpose. Similarly, namespaces when applied incorrectly can "specialize" classes unnecessarily and make them awkward to reuse elsewhere.

It can be important in a high-level namespace that carries an organization name to reserve a "Common," "Core," "Lib," or other namespace that can be used to store classes that can be reused across applications. Common examples are validation, where the rules for an enterprise-wide stock-keeping unit (SKU), account number, or invoice number are the same for proper format and length. For such a validator class, a good namespace may be something like Listing 7.

Listing 7. Using a common validation namespace
<?php
namespace MyCompany\Common\Validation;
class NotNullValidator {
...
}
?>

Here, the organization name is used as the high-level domain ("MyCompany"). The "Common" namespace is used as the project. Although this class was written perhaps while a specific application was written, the class can be used by any project in the organization. Finally, "Validation" is used as the domain for the class.


Using aliases

Although namespaces help you organize classes and avoid naming conventions, they do have the downside of longer names. Fortunately, PHP provides the ability to use an alias so that you can refer to the shorter alias name in your code. Listing 8 provides an example.

Listing 8. Using an alias
<?php
use MyCompany\Common\Validation as Validators;
?>

Naming conventions

It is consistent with other PHP conventions — such as the PHP Extension and Application Repository (PEAR) package naming and file names — to use uppercase camel or PASCAL naming conventions with namespace names. For instance, prefer the namespace in Listing 9 over that in Listing 10.

Listing 9. Uppercase camel or PASCAL naming
<?php
namespace MyNamespace;
?>

Avoid using naming and case conventions that are contrary to the rest of the PHP conventions.

Listing 10. Using a poor convention for case
<?php
namespace mynamespace;
...
?>

Conclusion

Namespaces in PHP are a way to organize your code, avoid naming collisions, and provide context for your classes, functions, and constants. Using a scheme or convention for your namespaces allows your code to be easily understood, as well as easily referenced and used.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Open source on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source
ArticleID=397023
ArticleTitle=Create better namespaces in PHP
publish-date=06232009