PHP Autoload and Singleton(ish) Model

Once every couple of years I take a month off from hacking away at the Store Locator Plus products and delve into some personal projects.  It is a way to learn some new things and try out new techniques without breaking the locator product.   With the locator being my primary source of income these days it is important to keep that intact while “trying new things”.

Some of the things I’ve been working on this week include Backbone, Bootstrap, React, Underscores, some new REST techniques, and a simplified object model for my internal “who cares about backward compatibility” PHP 7 projects.

One of the things I started playing with was autoload functionality.  Yes, it has been around since PHP 5, but it had a major overhaul in 7 and as such I think it is ready for production use.    Here are some things I learned along the way.

<tl;dr/>

If you employ autoloading classes use a singleton-style model.

Autoloading makes it tempting to litter your code with $obj=new Thing(); $obj->do_it();   and later in another function do a similar operation with $obj2=new Thing(); $obj->do_something_else();.

If you don’t use a singleton-style model you are spewing pointers all over the place and chewing up small chunks of memory.   Those pointers can be a few-hundred bytes to several Kb.  Memory usage is less of a concern these days but  allocation and de-allocation (garbage collection) takes time.    These days performance is a critical design feature of any web or mobile app.

The Self-Managed Loader

In some of my older PHP code I use a self-managed loading mechanism.  Throughout the code I use a require_once( “… class file …”) call.    The PHP file uses the class_exists() function to wrap the entire class as well as a small snippet of code that checks a “global list of instatiated object pointers”.   Before you start going off about “God objects”, that is not  how this architecture works.   The list is an array of object pointers I can test to see if a class is already instantiated and if it is I use that pointer.   The objects do not require the main list to function and can live independently as a truly independent object in most cases. I know with my application architecture that each class that uses that method should only EVER be employed once so I use the “object list” to enforce that.

However I didn’t like all of the require_once() calls littering my code.   It slightly more code clutter and my guess is that checking the file resources table in PHP on every one of those calls is likely far less efficient than checking a symbol table (or PHPs version of one).

And example of my “require registration” code…

private function get_string_default( $key ) {
   global $slplus;
   require_once( SLPLUS_PLUGINDIR . 'include/module/i18n/SLP_Text.php' );
   $text_to_return = $slplus->Text->get_text_string( array( 'option_default', $key ) );
}


if ( ! class_exists( 'SLP_Text' ) ) {
   class SLP_Text extends SLP_Object_With_Objects {
     public function get_text_string( $slug ) { return $slug; }
   }

   global $slplus;
   if ( is_a( $slplus, 'SLPlus' ) ) {
      $slplus->add_object( new SLP_Text() );
   }
}

class SLPlus {
  public function add_object( $object ) {
   if ( ! is_object ( $object ) ) {
      return;
   }
   $key = preg_replace( "/^{$this->class_prefix}/" , '' , get_class( $object ) );
   if ( empty( $key ) ) {
      return;
   }
   $this->objects[ $key ] = array( 'object' => $object );
  }
}

Every single class has the class_exists() test wrapper and the global $slplus with the add_object() call.   Inside the SLPlus class I have some utilities to simplify property names and use a __get() magic method so I can reference $slplus->Text to get the single instantiation of the SLP_Text object.

Autoloading

PHP 5 had an autoload function whenever you tried to instantiate a class but forgot to require the PHP class definition file.  You could write a function that said “go look in this directory and require the source”.    PHP 7 reworked this function and gave it a new name.  It is more intelligent about autoloading, to the point where the older autoload() is deprecated in PHP 7.2.    I’m going to only refer to the new”ish” spl_autoload_register() methods here.   The ramifications on HOW you implement this (the Singleton thing mentioned above) are the same regardless.

As noted, autoloading is a way for PHP to perform a last-ditch effort to keep code from crashing when you reference a class but forgot to include the source explicity in your code.    It is a great way to reduce code clutter.    The simple version is you write a function that takes the class name that is missing and tells PHP how to go about finding where that file might be in your source architecture, then usually requiring it to avoid a crash.

Here is the overview from my new RUIn (Are You In?  or “Ruin”) side project.   This is a base class for a custom WordPress Theme I am building for this project.    It does use the class test only because I need at least one global object to reference for other functionality in my theme.  It will also be helpful for the singleton-style model I will describe later.

In my projects I make sure all of my PHP file names match the class name they contain.  This is a general best practice that many PHP developers employ.  It makes your life a LOT easier as you can do some neat code tricks like you see here.   It also means moder IDEs , including my favorite phpStorm, can be far more intelligent about your code (auto-complete, grunt and npm task managers, syntax checkers, code smell, and a lot of other tools need far less wrangling).   The means I can use something as simple as the following code to instantiate my objects when needed.

if ( ! class_exists( 'RUInTheme' ) ) :
   class RUInTheme {
   
      public function __construct() {
         spl_autoload_register( [ $this , 'auto_load' ] );
      }

      public function auto_load( $class_name ) {
         if ( strpos( $class_name, 'RUInTheme_' ) === FALSE ) return;
         require_once( RUInTheme_DIR . '/inc/module/' . $class_name . '.php' );
      }
   }

   $GLOBALS[ 'RUInTheme' ] = new RUInTheme();

endif;

 

Now anywhere in my code I need a new instantiation of an object I can call $obj = new RUInTheme_Thingy(); and it magically includes the source.   My architecture dictates all modules go in the /inc/module/ directory and start with RUInTheme_ if they are part of this application.     Nice.  No more requires throughout my code.

Here is an extended example that loads up WordPress admin functions only when the user is a logged in user looking at backend admin pages or loads UI functions when someone is viewing a front-end page.   It means that the app is not loading memory up with code that is never going to be executed such as UI features that aren’t used on an admin page and vice-versa.

 

<?php
if ( ! class_exists( 'RUInTheme' ) ) :
   class RUInTheme {
      public $objects;

      public function __construct() {
         require( 'RUInTheme_Object.php' );
         spl_autoload_register( [ $this , 'auto_load' ] );
         $this->add_hooks();
      }

      public function __get( $property ) {
         if ( property_exists( $this, $property ) ) return $this->$property;
         if ( array_key_exists( $property , $this->objects ) ) return $this->objects[ $property ];
      }


      private function add_hooks() {
         if ( is_admin() ) RUInTheme_Admin::get_instance(); // Admin Only Stuff
         if ( ! is_admin() ) RUInTheme_UserInterface::get_instance(); // UI Only Stuff
      }

      public function auto_load( $class_name ) {
         if ( strpos( $class_name, 'RUInTheme_' ) === FALSE ) return;
         require_once( RUInTheme_DIR . '/inc/module/' . $class_name . '.php' );
      }


   }

   $GLOBALS[ 'RUInTheme' ] = new RUInTheme();

endif;

Now to extend my application I only need to add a class and matching file name in the inc/module/ directory and use new ClassName() in my code. Sweet!

The Un-Singletons

Now what about those singletons and the memory issue?

I quickly discovered that having super-clean readable code was cool but I was pissing memory all over the floor and mucking up my server.   That’s fine for my local Vagrant box (thought it was breathing heavy when hammering the app) but on a production server that would not be a nice “feature”.    Here is what I was doing as I didn’t need to reference the object just employ the methods:

/**
 * WP Hooks
 */
private function add_hooks() {
   if ( is_admin() ) new RUInTheme_Admin(); // Admin Only Stuff
   if ( ! is_admin() ) new RUInTheme_UserInterface(); // UI Only Stuff
}

Functionally this was fine.  The constructor setup the proper WordPress hooks and the methods did their magic whenever I needed them to.   Great clean clode.   Code that happens to piss memory all over the floor just for fun.

No, the memory leak was not a huge issue.  A small 320 byte pointer that was never referenced.  In reality the memory was not a leak as the architecture only calls these objects once and they are never re-used.  Whether or not I assigned the new object to a variable the memory consumption would not change.    Not a big deal until you start getting into larger more complex apps.

The problem with larger apps is you will likely end up with a class that has an object that is polymorphic, or has independent properties for each element of a list of objects, or some other recursive deployment.     In a very useless example, you would end up with dozens of 300-700 byte pointers hanging around a give PHP a lot more clean-up work with something like this:

function setup() { $obj = new Theme_Admin(); $obj->setup(); }
function update() { $obj = new Theme_Admin(); $obj->update(); }
function breakdown() { $obj = new Theme_Admin(); $obj->breakdown(); }

While this is an over-simplified example that can be optimized in many ways you can imagine this being part of multiple independent classes such as an AJAX or REST processor that can not be certain the Theme_Admin() object has been invoked and does not have public properties to share the instantiation.    For these to be truly independent objects they each must employ their own pointers to the object.   Luckily PHP 7 is smart enough to handle the object definition itself in shared memory , signficantly reducing memory load and increasing performance, but there is still a lot of excess overhead with this model.

There is a better way.

A Singleton Autoloaded Model

Use a PHP class version of a singleton by employing a static instance property in your class.    Add it to a public method and instead of using a new call to deploy an object you use your instance manager method.     This ensures all of your PHP references that use this model get back the same memory pointer.    Less overhead for PHP overall and with a large or highly recursive application a lot less memory usage.

Since I employ this method for nearly all of my classes in my application I create a base object that each of my auto-loaded classes will extend.    To invoke a new object I use the static call to the class with something like Theme_Admin::get_instance().   Much cleaner than a long require_once() with a path.

Here is the full example:

RUInTheme_Object

<?php
defined( 'ABSPATH' ) || exit;
if ( class_exists( 'RUInTheme_Object' ) ) return;

/**
 * Class RUInTheme_Object
 *
 * A class that some objects will extend when they need to be a singleton connected to the RUInTheme global object.
 */
class RUInTheme_Object {

   /**
    * Return an instance of the object which is also registered to the RUInTheme global less the RUInTheme_ part.
    * @return mixed
    */
   public static function get_instance() {
      static $instance;

      if ( ! isset( $instance ) ) {
         $class = get_called_class();
         $instance = new $class;

         $short_class = str_replace( 'RUInTheme_' , '' , $class );
         $GLOBALS[ 'RUInTheme' ]->objects[ $short_class ] = $instance;
      }

      return $instance;
   }
}

 

RUInTheme

<?php
defined( 'ABSPATH' ) || exit;
if ( defined( 'DOING_AJAX' ) && DOING_AJAX && ! empty( $_POST[ 'action' ] ) && ( $_POST[ 'action' ] === 'heartbeat' ) ) return;

if ( ! class_exists( 'RUInTheme' ) ) :

   /**
    * Class RUInTheme
    *
    * @property        array       $objects        Arrays of instantiated singletons.  The key is the class name less the leading RUInTheme_ part.
    *
    * Auto-registered singletons so our phpStorm autocomplete is smarter...
    *
    * @property-read   RUInTheme_StartARuin_Shortcode  StartARuin_Shortcode
    */
   class RUInTheme {
      public $objects;

      /**
       * RUInTheme constructor.
       */
      public function __construct() {
         require( 'RUInTheme_Object.php' );
         spl_autoload_register( [ $this , 'auto_load' ] );
         $this->add_hooks();
      }

      /**
       * Get our properties, including registered objects.
       *
       * @param $property
       *
       * @return mixed
       */
      public function __get( $property ) {
         if ( property_exists( $this, $property ) ) return $this->$property;
         if ( array_key_exists( $property , $this->objects ) ) return $this->objects[ $property ];
      }

      /**
       * WP Hooks
       */
      private function add_hooks() {
         if ( is_admin() ) RUInTheme_Admin::get_instance(); // Admin Only Stuff
         if ( ! is_admin() ) RUInTheme_UserInterface::get_instance(); // UI Only Stuff
      }

      /**
       * Autoload objects.
       *
       * @param string $class_name
       */
      public function auto_load( $class_name ) {
         if ( strpos( $class_name, 'RUInTheme_' ) === FALSE ) return;
         require_once( RUInTheme_DIR . '/inc/module/' . $class_name . '.php' );
      }


   }

   $GLOBALS[ 'RUInTheme' ] = new RUInTheme();

endif;

RUInTheme_Admin

<?php
defined( 'ABSPATH' ) || exit;

/**
 * Class RUInTheme_Admin
 *
 * Things that are run on admin pages.
 */
class RUInTheme_Admin extends RUInTheme_Object{

   /**
    * RUInTheme_Admin constructor.
    */
   public function __construct() {
      add_action( 'admin_enqueue_scripts' , [ $this , 'give_us_style' ] );
   }

   /**
    * Admin CSS
    */
   public function give_us_style() {
      wp_register_style( 'ruin_admin_style' , RUInTheme_URL . '/assets/sass/wpadmin.min.css' );
      wp_enqueue_style( 'ruin_admin_style' );
   }
}

The Object List

You may have noticed I still have a __get() method in the main class as well as the objects property.    Even with the singleton method and autoloading I find it far easier to reference my instantiated objects from auto-derived properties on the main object.    This way I know that all of my primary utilities can be referenced via $MainObj->ClassNameWithoutBase.

I can also be confident that since I’m using the Singleton style implementation I can also call my get_instance() for the classes I need whenever I am starting a logic path and later reference the methods.

In my example below I do manually define global $RUInTheme and provide a @var code hint.  This is so phpStorm auto-completes all my method calls and type-checks parameters in real-time (far fewer bugs, yay!).  I could get away with cleaner code by referencing $GLOBALS[‘RUInTheme’]-><classname>->method() but I opt for faster development and syntax checking over saving a line of text.

Here is the UI code from RUInTheme that makes use of the Singleton which auto-registers itself on the RUInTheme base object using a shorthand (dropping the RUInTheme_ prefix I use on all classses in this project).

RUInTheme_UserInterface.php

<?php
defined( 'ABSPATH' ) || exit;

/**
 * Class RUInTheme_UserInterface
 *
 * Things that are run on UI pages only.
 */
class RUInTheme_UserInterface extends RUInTheme_Object {

   /**
    * RUInTheme_Admin constructor.
    */
   public function __construct() {
      add_action( 'wp_enqueue_scripts' , [ $this , 'give_us_style' ] );
      add_shortcode( 'start_a_ruin' , [ $this , 'start_a_ruin' ] );
   }

   /**
    * Admin CSS
    */
   public function give_us_style() {
      wp_register_style( 'ruin_ui_style' , RUInTheme_URL . '/assets/sass/master.min.css' );
      wp_enqueue_style( 'ruin_ui_style' );

      wp_enqueue_script( 'ruin_ui_scripts' , RUInTheme_URL . '/assets/scripts/ruin_ui.min.js' , [ 'backbone' ] , RUInTheme_VERSION , true );

      if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
         wp_enqueue_script( 'comment-reply' );
      }
   }

   /**
    * [start_a_ruin] processor.
    *
    * @var RUInTheme   $RUInTheme
    *
    * @return string               The shortcode HTML.
    */
   public function start_a_ruin() {
      RUInTheme_StartARuin_Shortcode::get_instance();
      
      global $RUInTheme;
      return $RUInTheme->StartARuin_Shortcode->get_shortcode_html();
   }
}

RUInTheme_StartARUIn_Shortcode

<?php
defined( 'ABSPATH' ) || exit;

/**
 * Class RUInTheme_StartSomething_Shortcode
 *
 * Render the [start_a_ruin] shortcode.
 */
class RUInTheme_StartARuin_Shortcode extends RUInTheme_Object{

   /**
    * Display the HTML for [start_a_ruin]
    */
   public function get_shortcode_html() {
      $text['start_a_ruin']   = __( 'Create A Group Text' , 'ruin' );
      $text['list_name']      = __( 'Tell people what your list is about. ' , 'ruin' );
      $text['list_name_help'] = __( 'A short description so people know what your list is about. ' , 'ruin' );
      $text['create']         = __( 'Create' , 'ruin' );

      $HTML = <<<HTML
      <div class="container-fluid">
         <div class="row">
         
            <!-- column 1 -->
            <div class="col visible">
                    <button id="start_a_ruin_button" type="submit" class="btn btn-primary">{$text['start_a_ruin']}</button>                               
            </div>
            
            <!-- column 2 -->
            <div class="col start_step_one hidden">
               <form id="start_a_ruin_step_one">
                  <div class="form-group">
                     <input type="text" class="form-control" id="list_name" placeholder="{$text['list_name']}" aria-label="{$text['list_name']}" aria-describedby="list_name_help">                
                     <small id="list_name_help" class="form-text text-muted">{$text['list_name_help']}</small>
                  </div> 
                  <button type="submit" class="btn btn-primary">{$text['create']}</button>                              
               </form>
            </div>          
         </div>
      </div>

      <!-- Backbone View -->
      <div id="list-app">
         <ul class="list-list"></ul>       
      </div>

      <!-- Backbone List Template -->
      <script type="text/template" id="list-item-tmpl">
         <p><a href="/wp-json/ruinbot/<%= id %>"><%= name %></a></p>
         <p>ARN: <i><%= arn %></i></p>
         <button class=""remove">Delete</button>          
      </script>
HTML;

      return $HTML;
   }
}

That is the guts of a fully functional WordPress theme with custom shortcodes, a Backbone processor, and is easily extensible with self-checking code (thanks to phpStorms) and object loading.     It is memory efficient in the new responsive JavaScript app being driven by the WordPress REST API.

No, it is not the perfect model, but it is a smarter model for the architecture I am deploying.    Some of this may even find its way back into Store Locator Plus and some of the other projects I have online ; at least the PHP 5.2 compatible parts for my WordPress projects.   Maybe someday WordPress will bump the requirement to PHP 5.6 and I can make more use of some super-cool PHP tricks.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.