What is Namespacing?

cascade-creek-daylight-355637

by Aaron Reimann

March 7, 2017

Namespacing is something that’s been around in many other languages for quite awhile. In PHP, it was introduced at version 5.3. In PHP, they are designed to solve two problems:

  1. Name collisions between code you create, and internal PHP calsses/functions/constants or third-party classes/functions/constants.
  2. Ability to alias (or shorten) Extra_Long_names designed to alleviate the first problem, improving readability of source code.

When starting out with writing your own Plugins in WordPress, you can benefit from using Namespaces. The codex suggests prefixing plugin functions or to define your functions under a class. But the class would also need to be prefixed to avoid the collision problem stated above. They also can help organize your code through the directory structure and auto loading.

Below you can see an example of how you would namespace.

<?php

namespace S8;

class Slider {

    static function getSlides() {
        $slides = new \WP_Query();

        return $slides;
    }

}

From the example, you can see we can use a simple class name “Slider” and there is no risk of another plugin interfering with the same class name because they are under our namespace “S8”.  Also note, since we are using our own namespace, that if we want to use classes that our outside it, we’ll need to use the full path. So, if we need to use WP_Query, we have to make sure to escape to the global namespace and then class name.

If we were in our theme and wanted to call the get slides method, we would have to call the whole path.

$slides = S8\Slider::getSlides();

With this in mind, we can group code together and structure our files in a way that mimics the namespace paths.

Main_Project/
    src/
        Slider/
            views/
                slider-output.php
            Slider.php
    Main_Project_File.php

The above folder structure is pretty simple, but as the codebase grows, organizing in such a way can be beneficial to know where certain items are. Also, following the PHP PSR-4 standard with how you name your classes and structure you can take advantage of autoloading. This helps if you have a number of files and don’t need to worry about doing require_once.

related posts

Three Articles For GoDaddy

Writing articles on my personal blog and Sideways8’s blog has always been fun. I’ve been…

Opera Neon

Another Browser called Opera Neon

In 2000, I was using Windows 98 and ran Netscape, IE, Mozilla and probably a…

Three Things for WordPress in 2017

I recently did a talk at the Marietta WordPress Meetup that I co-lead concerning the…