News Archive
PhpRiot Newsletter
Your Email Address:

More information

Working With Non-Namespaced Components

Note: This article was originally published at Planet PHP on 29 March 2011.
Planet PHP

In my Beyond Frameworks talk, I explained how a component-based architecture can help answer some of the important (i.e. expensive!) questions you might face when creating long-lived apps that rely on a PHP framework. In this series of blog posts, I'm going to look at how to go about creating and working with components.

A component-based approach works well with the new namespace support added to PHP 5.3, and indeed I'm making full use of this in the components I'm building for this tutorial. But not everyone is ready to move to namespaces, and when you start to consume older components inside yours, you might run into errors.

Namespaces Recapped

The whole idea behind namespaces is to make life easier for developers, by doing away with having to type incredibly long class names all the time. For example, take the ConsoleDisplayLib component I recently released. In the pre-PHP 5.3 days, I would have had to define the classes it provides like this:

class Gradwell_ConsoleDisplayLib_StdOut { a }

a and then when I wanted to use it, I would have to do this:

$stdout = new Gradwell_ConsoleDisplayLib_StdOut();

A workable system, to be sure, and one that OO PHP programmers have used for many years, but hardly RSI-friendly, I'm sure you agree. With namespaces, however, things change. The class is now defined like this:

class Gradwell\ConsoleDisplayLib\StdOut { a }

Note the use of a\' instead of underscores. That's PHP's new namespace separator, and it tells PHP that the class StdOut lives inside the Gradwell\ConsoleDisplayLib namespace, which in turn lives inside the Gradwell namespace. Namespaces are just another kind of scope, like local scope vs global scope. Hold that thought, because it's these new scopes that affect our attempts to mix in non-namespaced code.

If I'm writing code that is part of ConsoleDisplayLib, to create a new StdOut object, I now only need to do this:

namespace Gradwell\ConsoleDisplayLib;

$stdout = new StdOut();

PHP automatically expands aStdOut' to mean aGradwell\ConsoleDisplayLib\StdOut', because I've used the namespace keyword to tell PHP that this code is part of Gradwell\ConsoleDisplayLib.

And that is where the fun begins.

Adding HTTP_Request2 To RepustateApi

I've made the choice to reuse the existing PEAR component HTTP_Request2. The PEAR project doesn't currently use namespaces; all classes defined by HTTP_Request2 exist in the global scope. So if I try to use HTTP_Request2 like this inside my Repustate API client:

namespace Gradwell\RepustateApi;


$httpClient = new HTTP_Request2($url, HTTP_Request2::METHOD_POST)

Truncated by Planet PHP, read more at the original (another 1990 bytes)