stephen.news

hypertext, words and more

PHP Namespaces

A screen full oh beautiful PHP

If you build or customize WordPress themes, coming across Namespaces are going to become more and more commonplace. I think they’re pretty cool. I have never enjoyed having to write (or parse for that matter), custom_functions_with_a_weird_long_name.

Steve Grunwell has a fantastic primer on Namespaces, and how to use them in WordPress. I also learned about Singletons (and their problems in a OOP environment) and why Namespaces are effective.

In short, functions are typically defined in plugins a variety of ways. Not long ago, developers might have written a function like this:

<?php
 
function get_recent_posts( $limit = 5 ) {
  return new WP_Query( array(
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'orderby'        => 'post_date',
    'order'          => 'desc',
    'posts_per_page' => $limit,
  ) );
}

Innocent, naive function writing.

Function name collisions are were pretty likely to occur, so we got longer and longer functions which led to Class encapsulations, so these functions began to make a mess of your codebase with global variable declarations. Steve goes on:

From here, developers seem to have split into two factions: the first, dead-set on removing global variables, moved toward the Singleton pattern:

class MyPlugin() {
 
  protected static $instance;
 
  protected function __construct() {
    // Made protected to prevent `new MyPlugin()` calls.
  }
 
  public function get_instance() {
    if ( ! self::$instance ) {
      self::$instance = new MyPlugin();
    }
 
    return self::$instance;
  }
 
  public function get_recent_posts( $limit = 5 ) {
    return new WP_Query( /* ... */ );
  }
}
 
# Usage:
$plugin       = MyPlugin::get_instance();
$recent_posts = $plugin->get_recent_posts();

Yikes, what a pickle… But, behold! The proper (and more maintainable effort) with Namespaces:

<?php
 
namespace SteveGrunwell\MyPlugin;
 
use WP_Query;
 
function get_recent_posts( $limit = 5 ) {
  return new WP_Query( array(
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'orderby'        => 'post_date',
    'order'          => 'desc',
    'posts_per_page' => $limit,
  ) );
}

What a wild and crazy ride! Seriously, give Steve’s post a full read.