Posted on

Get An Invite To Our New Locator Service

Go ahead and sign up for our Early Access Program to the My Store Locator Plus service.

My Store Locator Plus is an online subscription service that brings Store Locator Plus to ANY web technology stack.  WordPress, Django, Ruby, ASP.Net.    As long as you are hosting a site that can run JavaScript then My Store Locator Plus will work.

We are currently in the very early stages of development; what we call our “alpha release”.  It is far from being the final product but it IS functional and has been tested on various web technologies to see how well it can bring the Store Locator Plus service to non-WordPress sites.

We are now opening up our private invite to the Alpha Release of My Store Locator Plus.   The select few users that are granted access will help guide us in the features and overall user experience that will make it into our initial public launch coming in early 2017.

MySLP Locations July 2016 Alpha Release
MySLP Locations July 2016 Alpha Release

Continue reading Get An Invite To Our New Locator Service

Posted on

Store Locator Plus 4.5.09, Premier 4.5.09 and Add-on updates

Store Locator Plus 4.5.09

SLP was updated to version 4.5.09 to allow for compatibility with those users who have a lower PHP of 5.5 or lower. WordPress recommends PHP 5.6 but we realize not everyone can get their host to upgrade. WP does provide verbiage (click on the link) to send to your provider host if you are interested in helping put the pressure on. When you upgraded the base plug-in to 4.5.09 and if you had a lower version of ProPack installed, you will see a notice that disabled 4.5 version of Pro Pack. You still have access to it and can upload the latest version (4.5.07). All you need to do is log into your account and download the latest version from there as noted in an earlier blog.

Pro Pack, Tagalong, Pages = Power

As many of you have noticed there have been changes that affect some of our most popular add-ons.  The latest updates to these add-ons were made for compatibility reasons as Store Locator Plus continues to evolve on its way to become lighter, more efficient and will use less of your overhead.  Pro Pack and Tagalong have joined the ranks of LEGACY add-ons and will not be updated further since the functionality and features have been moved or added to the newer Power add-on. Legacy add-ons will continue to work with the SLP version in use at the time the add-on was purchased
Continue reading Store Locator Plus 4.5.09, Premier 4.5.09 and Add-on updates

Posted on

Boosting WordPress Site Performance : Upgrade PHP

As with every single WordCamp I’ve attended there is something new to be learned no matter how much of a veteran you are.   My 5th WordCamp at WordCamp US 2015 was no different.    There are a lot of things I will be adding to my system admin and my development tool belt after the past 48 hours in Philadelphia.

Today’s update that was just employed on the Store Locator Plus website:   Upgrading PHP.

Turns out that many web hosting packages and server images, including the Amazon Linux Image, run VERY OLD versions of PHP.    I knew that.   What I didn’t know was the PERFORMANCE GAINS of upgrading even a minor version of PHP.    PHP 5.6 is about 25% faster than PHP 5.3.    PHP 5.3 was the version I was running on this site until midnight.

WP Performance On PHP
WP Performance on PHP. Source: http://talks.php.net/fluent15#/wpbench

The upgrade process?  A few dozen command-line commands, testing the site, and restoring the name server configurations from the Apache config file which the upgrade process auto-saved for me.  EASY.

What about PHP 7?   That is 2-3x faster.  Not 2%.  100 – 200%.   WOW!    As soon as Amazon releases the install packages for their RHEL derivative OS it will be time to upgrade.

 

If you are not sure what version your web server is running (it can be different than command line on you server) you can find that info in the Store Locator Plus info tab.

SLP PHP Info
SLP PHP Info

The take-away?   If you are not running PHP 5.6, the latest release of PHP prior to PHP 7, get on it.  One of the main components of your WordPress stack will be running a lot faster, have more bug fixes, security patches, and more.

Posted on

PHP Switch Vs If Performance

When writing a complex application such as Store Locator Plus, you will often find multiple logic branches to handle a given task.   There are two oft-used methods for processing the logic; the If-Else construct and a Switch statement.    Since I am always looking to optimize the Store Locator Plus codebase for performance, some sites do have hundreds-of-thousands of locations after all, it was time to look into the performance-versus-readability of those two options.

The general consensus, though I’ve not taken the time to run performance tests with the WordPress stack myself, is that “you should use whatever makes your code easier to read are more easily maintained”.  For me that means using switch statements.    I find the construct much easier to extend and not cause inadvertent side effects.  Something I’ve learned in 20-plus years of working on code teams and in long-run projects like Store Locator Plus.

On the pure performance standpoint an if-else can be marginally faster if performing less than 5 logic comparisons.

PHP If Else Statement
PHP If Else Statement

Switch statements will often be faster at-or-near 5 logic comparisons as code optimization within C, and likely carried forth in the PHP psuedo-compiler, will often turn the 5+ logic branches of a switch statement into a hash table.  Hash tables tend to be faster with all branches of the code having equal access time.    Statistically speaking a large number of iterations will favor the equal access time model over the “first-fastest” model of an If-Else.

PHP Switch Statement
PHP Switch Statement

Possibly faster and always easier-to-extend and read, Switch will be my “weapon of choice” whenever I have more than  a simple 2-state if/else logic branch to be tested.

Posted on

Analyzing WordPress PHP Memory Consumption

XDebug Banner

This weekend I have been processing a large 200,000 location data file for a Store Locator Plus customer.   This is one of the larger files I have processed on my test system and it is the first file over 60,000 locations I’ve processed since Store Locator Plus 4.2 and WordPress 4.x have been released.    This large file processing and the geocoding required is taxing several systems in the Store Locator Plus hierarchy.  WordPress, Google OEM API calls, and the locator are all showing their weak spots with this volume of data processing.   They can all handle it to some degree, but maximizing efficiency is the key.

The temporary solution to most of the issues is to increase memory and process limits.   These are some of the key findings, as posted on the CSV Import documentation pages for Store Locator Plus:

Check your php.ini post_max_size setting if doing a direct file import versus a cron URL based import. post_max_size is typically set to 8 (MiB) on most servers.   This is typically enough for around 25,000 locations but it depends on how long your descriptions are and how many data fields you have filled out.   SLP 4.2.41 will warn you if you try to upload a file larger than your post_max_size limit.

Check your php.ini memory_limit setting and make sure it is large enough to handle the WordPress overhead plus the size of your CSV file times two.   The WordPress database interface and the CSV file processing will consume lots of memory.  The more plugins, widgets, and advanced theme features you have more more memory WordPress will use and the more PHP memory will leak over time. A setting of 256M is enough for approximately 15,000 locations.

Check your wp-config WP_MEMORY_LIMIT.   You may need to add this define to wp-config.php.  define(‘WP_MEMORY_LIMIT’ , ‘256M’).  The number needs to be equal-to or less-than the php.ini memory-limit.    It is the WordPress-specific memory limit and works with php.ini memory_limit.

Check your wp-config WP_MAX_MEMORY_LIMIT.   You may need to add this define to wp-config.php.  define(‘WP_MAX_MEMORY_LIMIT’ , ‘256M’).   This is the WordPress admin interface memory limit and works like WP_MEMORY_LIMIT for admin pages.

Set Duplicates Handling to Add especially if you know you do not have duplicate locations in your data.  SLP 4.2.41 further improves the performance when using ‘add’ mode by eliminating extra data reads from the database.

Set Server-To-Server speed to Fast under the General Settings tab unless you are on a shared host or experience a large number of uncoded locations during import.

Set the PHP Time Limit to 0 (unlimited) under the General Settings tab.   For hosting providers that allow your web apps to change this, the unlimited value will let the import run to completion.

Keep in mind Google limits you to 2500 latitude/longitude (geocoding) lookups per 24 hours per server IP address.  If you are on a shared host you share that limit with all other sites on that host.

However, even with all of these settings tweaked to fairly high values for my VirtualBox development system running on a MacBook Pro Retina host, the 4GB of RAM allocated to WordPress still is not enough.   The system eventually runs out of memory when the file gets close to the 45,000 location mark.  Luckily the “skip duplicate addresses” option allows the process to continue.    The “out of memory” error still rears its ugly head in the wpdb  WordPress database engine and is a problem for handling larger files.

Enter Xdebug and memory profiling.   Somewhere buried in the Store Locator Plus code, WordPress code, PHP MySQL interface, or PHP core engine there is a memory leak.  With a complex application environment finding the leak is going to be a monumental task.  It may not be something I can fix, but if I can mitigate the memory usage when processing large files that will help enterprise-class sites use Store Locator Plus with confidence.

Getting Xdebug On CentOS 7

If you follow my blog posts on development you will know that I run a self-contained WordPress development environment.  The system uses Vagrant to fire up a VirtualBox guest that runs CentOS 7 with GUI tools along with a full WordPress install including my plugin code.   This gives me a 2GB “box file” that I can ship around and have my full self-contained development environment on any system capable of running VirutalBox.   Here is how I get Xdebug connected to my local Apache server running WordPress.

Install xdebug from the yum install script.


# sudo yum install php-pecl-xdebug.x86_64

Turn on xdebug in the php.ini file


# find / -name xdebug.so

/usr/lib64/php/modules/xdebug.so

#sudo vim /etc/php.ini

zend_extension="/usr/lib64/php/modules/xdebug.so"

Check if xdebug is installed:


# php --version

... PHP 5.4.16
.... with xdebug v2.2.7

Enable some xdebug features by editing php.ini again.

Read about XDebug Profiling.

Read about XDebug Tracing.


# sudo vim /etc/php.ini

xdebug.default_enable=1  ; turns on xdebug any time a PHP page loads on this local server

xdebug.idekey="PHPSTORM" ; in case I turn on the automated listener for built-in PHP Storm debugging/tracing

xdebug.profiler_enable = 1 ; turn on the profiler which creates cachegrind files for stack trace/CPU execution analysis

xdebug.profiler_enable_trigger = 1;  turn on a cookie "hook" so third party browser plugins can turn the profiler on/off with a bookmark link

xdebug.profiler_output_dir = "/var/www/xdebug" ; make sure this directory is writable by apache and readable by your local user

xdebug.auto_trace = 1 ; when any page loads, enable the trace output for capturing memory data

xdebug.show_mem_delta = 1 ; this is what tells trace to trace memory consumption changes on each function call

xdebug.trace_output_dir = "/var/www/xdebug" ; same idea as the profiler output, this will be where trace txt files go

Restart the web server to get the php.ini settings in effect:


# sudo service httpd restart

At this point I can now open any WordPress page including the admin pages.   Shortly after the page has rendered the web server will finish the processing through xdebug and a trace* file will appear in /var/www/xdebug.   I can now see the stack trace of the functions that were called within WordPress with the memory consumption at each call.     This is the start of tracking down which processes are eating up RAM while loading a large CSV file without adding thousands of debugging output lines in the web app.

Be warned, if you are tracing large repetitive processes your trace file can be many GiB in size, make sure you have the disk space to run a full trace.

Posted on

Locator Updated With PHP Execution Time Control

Store Locator Plus 4.2.29 was released today with some minor enhancements that can make life easier for WordPress sites with large lists of locations or that are running on underpowered servers.

The latest release includes a new setting that allows a WordPress administrator to change the PHP Maximum Execution Time for scripts that are running, such as WordPress and the associated plugins.    The new setting makes it easier to override the standard limit set on my default PHP installations of 30 seconds per  a setting that is often defined in the inaccessible php.ini configuration file on the server.

The setting is not a ubiquitous option that impacts the entire WordPress environment.   The setting has been implemented in a way that makes it available to any WordPress plugin that wishes to access the Store Locator Plus options.    The primary use is to allow Store Locator Plus add-on packs to change the execution time allowed for certain operations.   The forthcoming updates to Pro Pack and Janitor, for instance, will leverage this new setting to allow more time for large location imports, exports, delete operations and related tasks to run.  The Pro Pack also employs the setting for downloading CSV reports of location searches-and-results.

The new setting honors security settings that may be employed by a server to prevent tampering with execution time.   Many shared hosting servers do not allow the PHP execution time to be changed “on the fly” to prevent one website on a server from taking over the entire server and effectively preventing all other sites on the same server from running effectively.     The now-defunct Safe Mode is one setting shared hosts may employ that can disable the Store Locator Plus execution time override.

The new setting ensures the larger location lists, those of 5000 or more locations, can be processed fully even on slower servers.     The setting defaults to 600 seconds and can be adjusted for any value from 1 second (not recommended) to infinite execution time by setting the value to 0.

Updates to the Pro Pack and Janitor will be published soon and take full advantage of the new setting.

Store Locator Plus Changelog

 

 

Posted on

Store Locator Plus Version 4.2.17 Released

Store Locator Plus version 4.2.17 was released today. The latest update has minor administrative updates as well as code refactoring for the add locations process. The updates should have no noticeable impact for typical users. Developers that have integrated the Store Locator Plus locations into other projects may need to update their code to accommodate the change of location in the location geocoding methods. Other updates in the Store Locator Plus plugin are related to administrative UI elements, adding new features to allow for dynamic updating of input fields to be disabled and enabled based on drop down selections. This can be useful for add-on packs with complex administrative setting interactions.

This update should not impact the administrative or user experience. The release is primarily to support new features in add-on packs such as the forthcoming Pro Pack schedule location imports.

Developer Notes

If you are using class.adminui.locations.php in your add-on pack or custom code and are calling any of the location add or geocoding methods you will need to require class.location.php. You can check the new class.location.php code to obtain revised method names for adding and geocoding locations. The most-oft-used method in the locations class is the add_to_database() method. If you have questions or problems please ask to join the CSA Slack channel via the contact form on the CSA website.

SLP Location Class Methods
SLP Location Class Methods

Store Locator Plus Changelog

Posted on

Senior WordPress Plugin Developer Wanted

Evil Genius banner

Join Charleston Software Associates

Charleston Software Associates (CSA) is the company that has created the popular Store Locator Plus WordPress plugin.   The plugin is running on an estimated 45,000 sites and has 5,000 registered users of the premium add-on packs. CSA is a single-man operation based in Silicon Harbor, aka Charleston SC USA.

The Agenda

It is time to take the company to the next level.   I need a “right hand man” to help me drive Store Locator Plus quality and presentation up a notch.     Once we are don a re-tooling of WordPress to create a full-blown SaaS Store Locator Plus implementation is on the agenda.

If you’re up for a challenge and want to create something cool with WordPress, this is your chance.

Your Skills

  • Well versed in WordPress coding.
  • Understand hooks and filters and have experience implementing them.
  • Possess extensive WordPress theme and/or plugin development experience.
  • Utilize proper object-oriented methodologies in their PHP implementations.
  • Use version control, git preferred, and comment documentation in phpDoc format.
  • Know and adhere to WordPress Core coding standards.

The “geek check list”:

  • PHP
  • CSS
  • HTML
  • MySQL
  • jQuery
  • JavaScript
  • git

Bonus points:

  • Bitbucket
  • Grunt
  • VirtualBox
  • Vagrant
  • phpStorm
  • SmartGit
  • Selenium IDE

You Are A Fit If…

  • You are an INDIVIDUAL, not a company and not an individual representing a company.
  • You have hands-on WordPress theme or plugin coding experience.
  • You write and speak English fluently.

I will give preference to applicants that are geographically closest to Charleston SC USA.   Communications improve with fewer time zone differences.   They are even better when we can meet over coffee or beer on a routine basis.

Your Reward

This is my “first man on board” position.   That role will grow to be the “director and main man” over the coming months.   As the company grows the underlings will be under your control.   You will help set the technical direction and future release features.

The position will start at 20-30 hours per week through the end of 2014 as we build the relationship, you learn the code, and we get things organized.    By the time January 2015 gets started the goal is to make this a full time gig.

You tell me what your compensation should be.    I will do my best to make it work.   At the start you will be serving in a contractor/freelance role.   Once we start building the team this can transition to an employee role if that fits your needs.

Contact Me with your introduction.  When the dialogue begins you can email me your resume if you have one prepared.

 

Posted on

WordPress Boolean Options and JavaScript : Handle With Care

JavaScript WordPress Banner

After chasing my tail for the past 5 days I finally uncovered the source of a bug in my code that was causing Store Locator Plus to not initialize properly on fresh installs. The culprit? How WordPress handles booleans. In particular, how WordPress handles the persistent storage and the JavaScript localization of booleans.

The important lesson:

WordPress option storage is done using STRINGS*.
* there is a caveat here: SERIALIZED options are stored with the data type,
single options (non-arrays) are stored as strings

WordPress JavaScript localization uses PHP and JavaScript DATA TYPES.

 

What does this mean for plugin coding?

If you are passing WordPress options that have been fetched from the wp_options table with get_option to JavaScript via the wp_localize_script() method your booleans that are set to true/false will be passed to JavaScript as ‘1’/’0′. On the other hand, if you are setting a PHP variable to true/false and passing that to JavaScript they are set as a JavaScript boolean value of true/false.

The difference is important.

In JavaScript you write this for booleans:

if ( myoption.booleanvar ) { alert('true'); }

However you write this for the string version:

if ( myoption.booleanvar === '1' ) { alert('true'); }

How did this break my code?

When my plugin environment loads for the first time it uses an array to store option defaults. Since the user has not yet set or saved the plugin options the get_option call returns an empty array and those defaults are employed. However my option array looked something like this:

$options = array( 'booleanvar' => true );

To further compound the problem, I introduced yet ANOTHER issue by converting what was previously a single-element option to a serialized array in the latest patch release.   Serialized data is MUCH faster.  When you are fetching/setting more than a single option for your plugin.   To be a good WordPress citizen I’ve been slowly migrating all my legacy options to a single serial array.   HOWEVER the update did something like this:

$old_option = get_option('booleanvar');  // singular boolean options are stored as strings '1'/'0'
$options = array ( 'booleanvar' => $old_option ); // $old_option is a string
update_option( 'my_option_setting', $options);
delete_option('booleanvar');

My code is a lot “deeper” than shown here, but the basic idea was to fetch the pre-existing value of the singular option and store it in my options array. I save it back out to persistent storage and blast the old non-serialized option out of the database. THIS conversion for existing sites works well as the singular option variables will store and retrieve boolean data as a STRING. Thus my option comes back as ‘1’/’0′ depending on how the user left it and all is good in JavaScript-land.

HOWEVER, if you note above the NEW DEFAULT is to set booleanvar as a boolean with a default value of true. When storing a compound option (named array) with update_option it stores and retrieves values using the DATA TYPE.

$options = array( 'booleanvar' => true );
update_option( 'my_option_settings', $options );  // serial options are stored as proper data types
$options = get_option( 'my_option_settings');

Here the $options[‘booleanvar’] is set to a proper boolean.

As you can probably guess, this creates inconsistency in the Javascript.

Why? Because my JavaScript has been written for the most common use case which is one where users have set and saved the plugin options at least once. The JavaScript code uses the string comparison code shown above, ( myoption.booleanvar === ‘1’ ). It works as expected every time after the user has saved the options at least once.

Why does it work after options are saved? Because WordPress returns the boolean variable as the string value ‘1’. You can see this for yourself by playing with the update_option() and get_option() functions in WordPress to store/get a boolean true value. Since my code uses the stored values if they are set my booleanvar is not taking on the default true setting after the first save, it is coming back as ‘1’ which is what JavaScript expects to see.

The Lesson?

Use string values of ‘1’ and ‘0’ for your WordPress option values any time you are not using 100% serialized option values. It ensures consistency throughout your application by following the precedence set by the WordPress get_option function.

Yes, you can get away with using boolean true/false values. It even makes the code more readable, IMO. However it can cause issues if you ever decide you need to pass those values along to your JavaScript functions with wp_localize_script() if you are not 100% certain you are using pure non-translated boolean variables throughout.

If you are ever uncertain of your true data types add a gettype($varname) debugging output to your plugin code. Remember that simple print_r statements will convert booleans to strings as well, use gettype to be certain of what flavor variable you have inside PHP.

Posted on

WordPress Password Protected Content Not Working

Jetpack

One of my sites had problems displaying password protected content this morning.    The site worked fine, but after supplying the password on the protected content the content area was blank.   It turns out JetPack plus some missing PHP modules on my Linux server were the culprit.

How did I find the issue?

WordPress debugging.    This is usually my first stop when trying to isolate a WordPress problem.    Go to the root install of your WordPress site and edit the wp-config.php file.   Look for the line:

define('WP_DEBUG', false);

Change it:

define('WP_DEBUG',true);

 

While you are in there turn this on as well.   This will allow you to quickly turn this feature on-and-off and then investigate the debug.log file in the wp-content directory.  You don’t want to leave debug mode on with a site that visitors are accessing.

define('WP_DEBUG_LOG',true);

When I make these edits I prefer to copy both lines and set one of them to false while leaving the other true, then comment out the pair of lines I am not using.   That makes it easy for me to go in and turn debugging on/off by swapping the leading comment (#) marker.

Now go to the offending page on  your site.     You should have the errors logging to the ./wp-content/debug.log file which will give you some hints.

JetPack Needs

In order to properly render protected content JetPack uses the XML Dom Document processor.    Make sure you have installed php-xml on your server.

The other package JetPack uses heavily is multibyte string support.   Make sure you have php-mbstring installed.

On Red Hat flavored Linux variants you can get everything in order by using these commands:

yum install php-xml
yum install php-mbstring
service httpd restart

Make sure you execute the restart on the web server so the PHP modules are loaded properly.

 

This may not fix the issue on your server, but the debugging and module searches may help some of you.

Good luck.

 

 

 

 

Posted on

Geeking Out With Netbeans and PHPDoc

I’ve been playing with phpDoc and NetBeans a lot lately.  I’ve found that having well documented code using the phpDocumentor 2 format makes for a much more efficient coding environment.   For one thing, if you have NetBeans setup properly and are using PHP classes that are fully documented, writing a line of code is as simple as typing a few characters.  NetBeans will find the objects you are looking for and list the properties and methods as you type.

That makes for some fast coding when typing something like $this->plugin->currentLocation->MakePersistent().  When everything is setup properly and the classes are properly documented I can type $t<tab>p<tab>c<down><tab>M<enter>.    While it may look like a lot of typing when spelled out essentially I am typing “$ttptcdtme”, or 10 characters instead of somewhere around 70.    Being 7x as efficient when writing thousands of lines of code is a HUGE bonus.

GitHub Markdown Docs for Code

Auto-complete shortcuts alone is one good reason to use a strong IDE like NetBeans along with a good code commenting/documentation solution like phpDocumentor2.   However tonight I found a cool new trick that I stumbled upon while trying to generate code documentation via GitHub.    I had learned a couple of weeks ago that I could use the command-line PHPDoc tool and a open source GitHub project called PHPDocMD to convert my code comments to XML and convert that to markdown (MD) that GitHub likes.   It creates OK results that are out on the public code repositories at Github.

So what is that new trick?  Well, there are 2 distinct parts.

Autogenerated HTML Docs for Code

Turns out there is a plugin for NetBeans that I’ve been ignoring.  For some reason I just happened to figure out that the “Generate Documentation” menu that appears when I right-click on a project in NetBeans actually has some use.

Yeah, I’m slow like that sometimes.

Turns out that under that menu is a submenu that has “ApiGen” and “PHPDoc” listed there.    Interesting.    That could be useful.

I went to the project, right-click, and select properties.  Sure enough, there is a setting for “PHPDoc” and it asks for a destination directory.  Basically asking “where do you want me to dump all the auto-generated documentation for your project?”.    Well it turns out that during my journey toward publishing code documentation on GitHub with MD, I had cloned the GitHub documentation repository to a local path on my development system.   I already had a folder full of code docs for my main plugin as well as several add-on packs.   So I pointed the output for my Netbeans “PHPDoc” setting to go there.

I go back, right click on the project, and select the Generate Documenation/PHPDoc.

Sure enough, NetBeans crunched my code comments and a few minutes later my Firefox browser window pops open and I see a pretty darn cool HTML site on my local box that has a full navigation menu for all of the classes I am using in my project, the properties, the To Do lists from my comments and more.  All this created because I’ve been taking a bit more time to fully comment the code.  Nice!

Settings Up For Auto-Publishing

Ok, so now on my dev box I have some pretty nice code docs that I can generate with a couple of mouse clicks.   That is helpful with a large project with multiple add-on packs.   But then I start thinking, why just keep it local?   The code is open source.  I have other developers that want to learn how to tweak the code for their own purposes.  I have third party developers looking for documentation and examples on how to do things so they can write efficient add-on packs.    Why keep the info all locked up on my dev box?

Well, I learned a neat trick a couple months ago with NetBeans.    I can have a local git repository on my development system but setup NetBeanswith a new “remote source” project.

So here I am with my commented code in my WordPress plugin directory that is fully commented and connected to a GitHub repository.   In another “docs only” directory outside of WordPress I have my PHPDoc generated HTML and MD files that I was previously only publishing to GitHub Wiki Pages, but now thanks to NetBeans I am also surfing locally on my dev desktop.     I realize I can auto-publish these code docs to my public website.

I create a new NetBeans project right next to my plugin code project.   I call it “store-locator-plus-codedocs” and set it up as a new PHP Remote Source project.   I tell it the local source on my box is the folder that I was storing the PHPDoc and MD files in for GitHub, which now contains my NetBeans-generated HTML files as well.    For a remote location I tell it to use my SFTP connection to the Charleston Software Associates website.  I jump on my website and make sure there is a new codedoc directory with a blank readme.txt file there.  If you don’t have SOMETHING for NetBeans to download from the remote source it thinks you screwed up and won’t continue…. minor flaw IMO, but easily remedied.    I then click OK.  It shows me the readme.txt with a checkbox to download it.    Click OK and BAM… there is a new project with the blank readme.txt plus all of the MD and HTML documents that were already on my local dev box.

OK, so kind of “so what” at this point, but here is where it starts getting cool… at least from a geek perspective.

Push The Initial Content

Now I need to “seed” the public website with the already-created content.   In NetBeans it is easy enough. Just highlight all the files in the project, right click and select upload.    Within a few minutes the entire HTML sub-site is uploaded to the server.   Just like any FTP program.   Nothing to it.

However now if I make any changes to those file with the editor two things happen, it saves a local copy on my dev box and it auto-publishes that updated to the live server in near-real time.    Since my local dev box has version control via GitHub, I can also quickly commit and push those edits also from inside NetBeans and make sure they are saved to the code repo.

But… I’m not going to ever edit those docs by hand.  They are auto-generated code documents that come from my well-formatted comments.  So the RIGHT way to edit them is to continue cleaning up and augmenting the code comments to make sure they are PHPDoc compliant.

So that is kind of cool.  My code docs are now auto-posting to my live server, saving on my dev server, and are one click from being saved and committed back to GitHub.  I can even add on more step and create a second copy in MD format for publication right next to the source code on GitHub.

But this is what really made me think “shit this is kind of cool”…

Auto-Publishing Code Comments

So I have all this stuff setup, my code project and my documentation project are both open at the same time in Netbeans.    I forget all about it as I start getting back into code writing.     I edit a method for one of the add-on packs and of course I go and update the comments about that method to reflect the latest changes.  I see another comment that is not complete and fill that out.

Save the code.  Commit the code so it publishes to GitHub.

A few more edits to code and comments later I decide… let’s generate the documentation before I sign off tonight…

I right click on my code project and select “generate documentation”.

Auto-magically the documentation project updates itself.   It saves a copy locally to my dev box with the new docs in place then auto-publishes to the public website with no intervention on my part.   As I setup the rest of my plugins with this system you will be able to find all the code docs on the bottom of the Technical Docs page on my site.   You can see my first auto-published work for Tagalong here, though I’m nowhere near done cleaning up the comments and naming conventions on my method to make this all “gussied up” for public consumption, but it’s a good start.

Maybe I’m just extra-geeky, but I thought that was cool… especially when the code docs actually look pretty darn good IMO, especially since they were created from nothing but /** This method does something.  @var string $this – does that **/ comments in the code.

I also know that with a few lines of script I can not only save locally and publish nice looking docs to my public site but also commit the code back to the GitHub repository while auto-generating the duplicate MD docs for the GitHub Wiki.

Yeah, I’m a Code Geek… and I’m not ashamed to admit it.

Posted on

Netbeans, phpDoc, and WordPress

A posting from our private “Tech List”, a list I share with select tech geeks mostly from the days at Cyber Sprocket Labs.   We tend to share high end tech tips that only geeks would find interesting.    I am posting here for easy reference for “The Tech List” groupies.

My Intro To Netbeans

9 months ago Chase was showing me NetBeans on his desktop.   It had some cool features for PHP like auto-complete and some very handy code lookup tools that reminded me of Visual Studio without all the weight.

 I wish I had learned about the NetBeans environment a long time ago.    NetBeans+ GitHub + SmartGit have made my coding at least twice a productive when it comes to PHP work, especially with complex WordPress plugin code.
In the past few months, while working in NetBeans, I’ve been refining my phpDoc skills.  This is EXTREMELY handy in making coding far more productive.    Here are some of the things I’ve learned that I wish we had all known about at Cyber Sprocket.    With the right tools it makes coding for people with senility (me) easier.

Effectively Using Netbeans for WP Dev

1) Wrap your ENTIRE plugin into a single instantiated object.
My plugin invocation now is basically something along these lines:
DEFINE(blah,blah) // a few of these help with WordPress stuff, like plugin version
class MP {
}
class MP_Error extends WP_Error {}
add_action('init', array('MP','init');
That is pretty much it other than the singleton.
2) Learn how to create and use singletons PROPERLY in WordPress
It must be a static method.
It should return itself as an instantiated object.
Set minimal properties as needed, not the entire WPCSL object here.
public static function init() {
    static $instance = false;
    if (!$instance) {
        $instance = new MP;
    }
    return $instance;
}
3) phpDoc the class
In netbeans you go back to just above class MP {} and type /** after starting the frame of the class with properties and methods in place.
It will AUTO-CREATE the template PHP docs.
First line of comment = 1 line description
Lines 3..m = a longer description if you’d like
Lines m+1..n = the properties defined with @property, @property-read, @property-write    (the setters/getters with r/w, r, w status)
These property lines, like variable lines are simple:
@property-read <type> name  description
for example
@property-read string plugin_name the plugin name
This indicates a read-only property for the object.
4) phpDoc the methods
 
Like classes, but NetBeans is even better with the docs, you write the function first.   Then go before the function foo() line and type /**.   NetBeans will create the entire phpDoc template.   You update it to give it the “hints”.
This is something I use a LOT now and you’ll see why in a moment.   Here is an example from WPCSL_Settings add_section:
Old school:
/**
* method: add_section
*
* does stuff
*
* params:
*     [0] - named array, blah blah
**/
New:
/**
 * Create a settings page panel.
 *
 * Does not render the panel.  Simply creates a container...
 *
 * <pre><code>
 *   $mySettings->add_section(array('name'='general'));
 * </code></pre>
 *
 * @param array $params named array of the section properties, name is required.
 **/
5) If your phpDoc property/variable type is a specific OBJECT then NAME THE OBJECT. 
For example:
class MP {

   /**
    * The WPCSL settings object, shortcut to the parent instantiated object.
    *
    *  @var wpCSL_settings__mp
    */
    private $wpcSettings = null;

}

Why I Am More Productive

Now here is why all these tips with phpDoc are useful and how I’ve slowly made my coding at least twice as efficient.
NetBeans defaults to having code hints and auto-fill turned on.   The cool part about this is it will do a few things like tell you when a required param is missing and flag the line as an error, the same way it does with blatant PHP syntax errors.    If you are creating some new code and you pause for a second with a partially written invocation then it will show you the possible options from a list of PHP functions, custom functions, or methods from objects you’ve phpDoc’ed properly.
Thus, I do something like this:
$this->wpcSettings->a   <pause>
It now shows me all the methods and properties in the WPCSL Settings Class that start with a in an in-place drop down list.
I cursor down to add_section and pause.
It shows me the full documentation on the method including my code example, the required parameters and more.
I press enter, it drops the completed method along with the first prototype in place, I cursor down to select from the various templates, for example if secondary parameters are optional, press enter and if fills out the entire code block.
I then modify the prototype to fill in my settings and I’m done.
If you do this right you can be ANYWHERE in your code as deep as you need to be.   You never have to go looking for the source, especially if you’ve written decent phpDoc comments.
I used to find myself split-screen looking at the source method or property code to see what it did or how it worked.    Now I spend time documenting the methods or properties in a verbose phpDoc comment and I never have to look at the code again.

Key Points

If you do NOT wrap everything inside a parent class it takes a lot longer to pop up the help.
If you just use the lazy @property object $myvar (or ‘mixed’) syntax you do not get to see all of the methods whenever you newly instantiated object is referenced by the variable name.
If you use things like public, private, setters, getters and use the matching phpDoc elements like @property-read  then NetBeans warns you if you do something illegal like try to directly SET that property.

A Day Older, A Day Smarter

I know some of you probably had productivity helpers like this while at Cyber Sprocket, but if I had known then what I know now I’d have been insisting that we all learn and properly implement phpDocs as our commenting standard.
An as you all know the other “freebie” with this is I could easily generate a full HTML (or markdown) site with all the classes, methods, and properties of any plugin with a few short commands.   I’ve not done that yet but will play with that sometime in the near future.    I need to figure out how to bake it into WordPress content at charlestonsw.com but I think it would be cool to have an entire plugin + wpCSL documented in an easy-to-browse format on the web.
Posted on

PHP Pretty Print XML

I have been working on MoneyPress : Amazon Edition to get it updated for the latest API release and bring it into the Charleston Software Associates stable of products.  Along the way I found myself needing to debug the XML being returned from the Amazon Product API.   Here is a quick trick for doing that.

...
$returnedXML = $result['body']
$xmlDoc = DOMDocument::loadXML($result['body']);
$xmlDoc->formatOutput=true;
print '<pre>' . htmlentities($xmlDoc->sveXML()).'</pre>';
...


Posted on

Passing PHP Variables to JavaScript

One of the things we do fairly frequently in our WordPress plugins is pass PHP variables to JavaScript.   We use this methodology to send a number of dynamic elements to the JavaScript processor without having to do AJAX or JSONP calls after the script has loaded.  Pre-processing and passing variables into JavaScript when the script is loaded is a far simpler mechanism.

 WordPress provides a simple, yet oft overlooked, method for getting your PHP data into JavaScript.   Using wp_localize_script() quickly maps a PHP named array to similar structure in JavaScript.    To do so you follow two simple steps:

1) Register or Enqueue your script.
see: http://codex.wordpress.org/Function_Reference/wp_enqueue_script

2) Localize your script.
see: http://codex.wordpress.org/Function_Reference/wp_localize_script

We have found some caveats for some themes.   Most importantly, make sure you select for “late loading” or “load in footer” so the script can be localized BEFORE it is rendered in the browser.  The other option is to register the script using wp_register_scripts() in the wp_enqueue_scripts hook then later load the script in a wp_footer hook using wp_enqueue_scripts().     Just keep in mind that not all themes support wp_footer().