Posted on

Speed Coding With phpStorm and WASD Keyboards

WASD Keyboard In Action

I’ve been coding a LOT more than usual over the past 3 weeks.    So much so that I’ve started having issues with my wrist, likely early onset of carpal tunnel which I would prefer to avoid.    I did a few things today to help offset that.

WASD Keyboard

The first was to buy an 87-key CODE keyboard from WASD.   This allows me to move my mouse a lot closer to “center” on my desktop.  Since I rarely use the numeric keypad or media keys, this is a good trade-off.  “Cut off” the numeric keypad and make the keyboard a lot narrower.   I’m not sure if I like the old-school clackety-clack of the Cherry MX Brown switches, but it has a great feel so I may get used to it.     Great backlighting as well.

WASD Keyboard In Action
WASD Keyboard In Action

One downside that I’ve already discovered is that the CTRL key through ALT key on the left side are more than a half-key position to the left of my old keyboard.  That makes the “reach” for CTRL-V (paste) keystrokes further apart than I like.    On the plus side, the full size / full travel keys have me looking down to validate my keystrokes far less often.  Overall I feel like I am typing much more quickly on this keyboard.  Amazing how much the tactile feel makes a difference in that regard.

New keyboard, less right-wrist travel especially for the mouse.   With another service launch coming this fall I expect a lot more coding; hopefully this change will eliminate the potential for carpal tunnel.

phpStorm Tricks

The other thing I did when getting the new keyboard, mostly due to changes in the keys that OSX recognizes, is setup some keyboard shortcuts in phpStorm.    I also learned some neat shortcuts I need to add to my daily routines.  Here are two of the most productive shortcuts that have my hitting a LOT fewer keys.

^Y = delete a line

This is going to save me from the old-habit ctrl-left-arrow , ctrl-shift-right-arrow, delete keystroke.   8 keystrokes down to 2.  Wish I discovered that one long ago.

Live Templates

This is HUGE.  Why didn’t I know about this 2 years ago?   What is a live template?   It can be a lot of things, but my simple version is using it as a permanently-saved copy & paste buffer for text I type frequently, especially during debugging.

What this does is sets up an auto-complete hint when you type in certain snippets of text (abbreviations).    For example, I have an echo statement I use when doing “quick & dirty debugging” in phpStorm.  It is faster than xdebug and all that complexity.    I have been manually typing in this long echo statement for years, something like echo “====== ” . get_class() . ‘::’ . __FUNCTION__ . “<br/>\n”;

I highlight that code, and select “Tools/Live Template”.    I then assign a shortcut, in my case I chose ‘ecof’ so it does not conflict with other PHP auto-complete hints.   Now I can simply type ecof-tab in phpStorm and it will auto-complete the line , replacing ecof with the entire echo statement above.

Cool, right?!

 

Now if phpStorm would just fix their newly-introduced “feature” in version 9 so I can get back the extra keystrokes I have to type every time I end a phpDoc comment line with a period (<sarcasm>which NEVER happens </sarcasm>) and they decide to auto-complete that as “.@deprecated”.

 

Coding Smarter…

Way less typing.  Faster code.  Less carpal tunnel.

I call that a win for today.

 

Posted on

CentOS 7 aapt libz.so.1 ELF and Missing Lib

While building an Android Studio app the build failed with aapt errors.   The aapt part of the build started off with a libz.so.1 missing error.    Turns out I had already installed the zlib library with yum install so libz.so.i already existed in /usr/lib64/.    The problem was with the library path.   That is easily fixed.

Put these commands in your ~/.bashprofile as well:


# LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib64/;
# export LD_LIBRARY_PATH

However the ELFs were not happy.    For those that don’t know what an ELF error means, it has something to do with byte offsets and library file formats.  Turns out it is a cryptic way of telling you the program is trying to load a 64-bit version of the library it needs instead of the 32-bit version.

Again an easy fix;

# sudo yum install zlib.i686

# LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/;/usr/lib64/;
# export LD_LIBRARY_PATH

The .i686 versions of the yum install kits are the 32-bit versions of the libraries.  They are placed in the /usr/lib directory.  Setting LD_LIBRARY_PATH helps the 32-bit dynamically linked executable find the proper link library.

Now on to building this Android app on my CentOS dev box.

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

Back To Coding

10 days, 7 pounds, and 67 emails later I am finally getting back online.    While I’ve managed to sneak in a few coding hours between entertaining guests and partaking in the awesome “foodie’s playground” of Charleston South Carolina, I’ve essentially been “unplugged” for the week.    Today it is time to get back to the code.  On my short term agenda:

Get Tagalong updated & published.

Tagalong has been neglected for a while.   I am pushing to get the new release out there so it works properly with Store Locator Plus 3.9.    Along the way I’ve been making some updates to the Store Locator Plus core to better support Tagalong.   Most of the changes to the main plugin will be hidden elements but it will make for a better way of adding “deep data” to store locations without hacking up the database every time.   Tagalong was already doing this which is why Store Pages was needed, however the new release is being crafted in a way that ANY add-on pack could use this methodology WITHOUT requiring Store Pages.

It is a lot of work, but I will be putting my “head down” and focusing on Tagalong code and the core plugin changes required to support.

Without further adieu… time to code…

 

 

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

Using Netbeans

Chase introduced me to Netbeans a couple of months ago.   It looked cool, but as with any dev tools there is some inertia involved in switching to a new editor.

I’ve been using Netbeans on my Linux dev box for about a month now.  While there are some quirks and some problematic areas with Netbeans, overall I have grown to like it more than jEdit, gvim, WinEdit and a handful of other code editors.    It is well balanced between the powerful, but often way to “heavy”, Visual Studio platform and the weaker editors like jEdit.
My favorite features I’ve come to discover & use on regular basis:

“Projects”

Netbeans will create projects based on current source directories.  Tell it the basic project type, such as PHP, and the starting file.  It tries to be intelligent about the structure of your code by doing semi-intelligent crawling.  It does a decent job.  The thing I really like about this is now that I have a dozen source directories setup as projects I can use the other tools (see find below) to locate stuff wherever it may reside.

“Find In Project” (ctrl-shift-f)

Netbeans will build a project based on a source directory you specify.  It crawls the source and builds a semi-intelligent index, which is a nice feature for “object browsing”.   However this quick search tool is my “go to” for locating “stuff”.    You can easily setup include/exclude patterns using system tools like “exclude this folder” or regular expressions.   The regex include/exclude is easy to use and super-powerful.     This same tool allows you to search “all projects”, “all open projects” or just the current project.

“Navigate”

Highlight a function or variable and right-click.  Use Navigate to find the definition or all occurrences (usage) of the same variable/function/thing-a-ma-bob.   Very nice and cuts down on my “find in project’ searches, especially when I want to modify a definition.

“Smart Complete”

I’ve not seen this in a decent PHP editor before, but it works much like the Visual Studio tool.  Start typing a method/function name and it pulls up all possible methods/functions and their property variants.  If you have optional params it lists those as different variants.  If your commenting on the declaration is well formatted it will also show you the description of the function, what the parameters are meant to do and more.     Scroll, pick one of the prototypes from the list and press enter and the call is put into the inline code, press tab to jump to and replace each param.

“Commenting”

This kind of goes with “Smart Complete”.    It took me 6 weeks of using Netbeans to find this because I NEVER write the code first then add the comment block.  I always put a stub comment first, then go back and fill it in.    I happened to paste in a function from elsewhere that had no comments, went above it and typed “/**”.   Netbeans automatically created a comment block with all the params listed.  That was cool.
You can learn more about auto-created comments and auto-completion here:

Summary

So I’ve grown to really like Netbeans.    Yes, it has some issues but overall the benefits outweigh the problems.
I know Eric has a plethora of Emacs tips & tricks he’s shared over the years.   What about others?  Do you have a favorite editor or IDE?   What are the cool tricks you’ve found?   Or if you use Netbeans, what other shortcuts have you discovered to help you manage/write code?
Posted on

Software, Reborn

phoenix

A month of turmoil.    That pretty much sums up August.

September is a month of rebuilding.    Slowly, but steadily, I am getting back to the things I love.  Coding.  Websites.   Creating.

Hopefully by the time October rolls around the dust will have settled and routine product updates will be rolling along again.  Cool new features on existing products will start to come out more frequently.    New products will come out, and overall things will improve for everyone.    It will take a while to clean up some messes and to extract the knowledge we need from the old Cyber Sprocket environment over to our new home.   But it will happen.

Before long you should be seeing new things coming your way to help make your website even cooler.     In the meantime please bear with us and keep your feedback and suggestions coming.