Profile WordPress Cron Jobs With VVV

I recently found that I needed to Profile WordPress Cron to figure out the best way to improve the processing time on background file imports.

In an effort to better handle on large location imports in Store Locator Plus, I re-architected the Power add on to split the process into 3 steps.   The first step uploads the file to the server; something that is typically fairly fast and only ties up a user’s web browser for a few minutes as most people are no longer on dial-up.   The second step, the reason WordPress Cron is now in play, is to fire off a background process via WP Cron to then parse the CSV file.     This second process is the one I want to profile.

Luckily I am using a typical VVV setup as part of my development environment.   It has Webgrind, a PHP cache grind file reporting tool, already enabled “out of the box”.   I only need to run the debug_on command from the Virtualbox command line and then add &XDEBUG_PROFILE to the end of any URL request to get a view into what functions are called and how much CPU time they are eating up.

Things get tricky if you want to profile WordPress Cron processes though.    Since they are fired off from WordPress automatically, how do you add a GET variable?
Read More

Building Selenium IDE TNG On MacOS

Download MacPorts from  https://www.macports.org/install.php

If you had a terminal session open, close it and start a new one to reload the environment path.

Check the port command is available.

/opt/local/bin/port

Install yarn.

Check yarn is running.

1.0.2

Login to your GitHub account and fork the selenium-ide repo so you can contribute patches back to the source.

Clone the repo to your box:

This creates a selenium-ide directory under the current directory.

Go to that directory.

Add some missing yarn packages:

Build the extension.

Stuff…stuff…stuff…

  [19] ./LocatorBuilders.js 13.3 kB {0} [built]

    + 5 hidden modules

Child html-webpack-plugin for “panel.html”:

     1 asset

       [0] ../node_modules/html-webpack-plugin/lib/loader.js!./panel.html 14.9 kB {0} [built]

        + 3 hidden modules

  Done in 3.05s.

You are now ready to add the extension to Chrome or Firefox.

Open Firefox version 55 or higher and follow these instructions:

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Temporary_Installation_in_Firefox

  • enter “about:debugging” in the URL bar
  • click “Load Temporary Add-on”
  • open the extension’s directory and select any file inside the extension.

In this case you’ll look for the selinium-ide/build/manifest.json file and select that to enabled the IDE.

You should now see the Se button on the browser and when clicked get the “Selenium IDE TNG” window which is very much a work in progress.

Selenium IDE TNG 2017-09-20_15-41-41.png

Why You Can’t Buy A Tesla In South Carolina

The bottom line: The Car Dealer Lobbyists

That’s what it all boils down to.   The states with the biggest car dealership and oil company presence have paid… I mean “talked to the”… legislators in their state to make sure that pesky little electric car company does not cut into their business.   Originally states passed laws to protect dealers.

Back in the early 50’s the “Big Three” wanted to focus on building cars so they franchised sales to dealers.    The dealers would spend their own money to introduce a brand of car they loved to a local market.   They spent a lot of money and time to get people to love their Ford or Chevy and make sales.

Then they got scared.  The car manufacturers would tell them they had to take cars nobody wanted but they built anyway like the Pinto or they’d stop getting ANY cars.   Even worse, the manufacturers threatened to open a competing dealership right next door.   And just like that the lawyers and lobbyists were involved and legislation was created to protect the dealers.

What people didn’t anticpate, which legislators often do not when paid to write laws, was that dealers like Hendrick here in the Southeast would become billion-dollar companies.   Or that some manufacturers, like Tesla, would never allow franchises and thus not pose unfair competition to a “small local guy that built up brand awareness for them”.

So here we are today with 6 states having an outright ban on Tesla selling cars to consumers.  It is no coincence all 6 states have a huge “legacy auto industry” presence such as Michigan with the Big Three auto makers, Texas with the oil industry, and South Carolina with the largest auto dealer in the nation.

Interesting twist, North Carolina also is under the thumb of Hendrick but The State also has significant ties to the financial industry.   The battle has gone back-and-forth with Tesla banned from selling in some counties but not others.    I guess Elon Musk’s background as a financial services billionare is a fairly even battle with Hendrick’s dealership influence.    At the moment you can drive 3 hours from Charleston to buy your Tesla in North Carolina.  For now.

Here is an excellent article from EcoWatch that explains it in more detail.

 

My Tesla Referral code for those looking for free supercharging and a $1,000 discount:
http://ts.la/lance6549

Wind and solar power are saving Americans an astounding amount of money

From Vox via Apple News:

Wind and solar power are subsidized by just about every major country in the world, either directly or indirectly through tax breaks, mandates, and regulations.

The main rationale for these subsidies is that wind and solar produce, to use the economic term of art, “positive externalities” — benefits to society that are not captured in their market price. Specifically, wind and solar power reduce pollution, which reduces sickness, missed work days, and early deaths. Every wind farm or solar field displaces some other form of power generation (usually coal or natural gas) that would have polluted more.

Read more…

 

To join me in helping the environment by using solar powered lawn care, check out Earth Friendly Landscaping.

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.

%d bloggers like this: