Gareth Redfern developer, cyclist & coffee lover

Namespacing In PHP

Posted by Gareth Redfern
Category: php

Using the example project I have set up lets take a look at how Composer uses namespacing which allows us to use the Monolog package. Open up the vendor folder and view the Monolog package. You will see a src folder which is where the Monolog code is stored, you will also see the composer.json file for this package, open it up in a text editor or use the github link to view the file. Composer implments namespacing in this file by first looking at the name value:

"name": "monolog/monolog"

This says that the vendor is monolog and the package is monolog, if you then scroll down to line 40 of the composer.json file you will see that it provides the directory that the source code can be found and maps it to the Monolog namespace.

"autoload": {
  "psr-4": {"Monolog\\": "src/Monolog"}
}

Open up the Logger.php file which is found in the src/Monolog folder. Scroll down to line 12 and you will see that this file has the namespace of Monolog. The first class in this file is called Logger, with namespacing in place (via the autoload.php file) you can now use this class by simply typing Monolog\Logger instead of the full file path:

require 'vendor/autoload.php';

$log = new Monolog\Logger('name');

In the code above Composer has made namespacing possible by autoloading the file and then providing namespacing to the Monolog\Logger class.

Aliasing A Directory Path

The second example of using namespacing to shorten your code can be found by setting an alias to a class name. For example in the sample project’s index.php file you could create an alias that points to Monolog\Logger, to do this you need to add the following line of code just below the require statement:

use Monolog\Logger;

Now instead of typing out Monolog\Logger('name') every time you can simply shorten things down to Logger('name'). Another example would be shortening ` Monolog\Handler\StreamHandler() down to StreamHandler()`, again you will need to add the following code just below the require statement:

use Monolog\Handler\StreamHandler;

It probably helps to now see the full index.php file with namespacing in place using aliases to shorten our code:

<?php

require 'vendor/autoload.php';

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger('name');
$log->pushHandler(new StreamHandler('app.log', Monolog\Logger::WARNING));

$log->addWarning('Foo');

echo "Hello World!";

It does take a little time to get your head round but once you understand how namespacing works it is a very powerful and clever way of avoiding conflicts when naming your classes.