Contact Us

What is Namespacing?

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.

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.

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

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.

ABOUT

No Comments Yet

Leave a Reply

Your email address will not be published. Required fields are marked *

We would love to hear from you!

Please fill out this form and we will get in touch with you shortly.