What is Namespacing?

The Blog

What is Namespacing?

cascade-creek-daylight-355637

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.

» More content from:

Aaron Reimann

DNS, Mailgun, and I'm Losing My Mind

By Aaron Reimann - Oct, 01 2018

Development

Sideways8 Sponsors the WordCamp Atlanta 2018

By Aaron Reimann - Jun, 06 2018

WordPress

Three Articles For GoDaddy

By Aaron Reimann - Jun, 04 2018

Business

Related Posts

A stronger Dragon Army is here.

We’ve been acquired by one of Atlanta’s fastest-growing agencies, Dragon Army. Through this partnership, we are proud to offer expanded capabilities in the areas of web, mobile, content, and branding to better serve our clients and partners. Excited to be a part of the Dragon Army family!

Learn more Got it
Hexagon