Namespaces and Objects

Markdown editing for WordPress.

Parsedown Party is a new WordPress Plugin I wrote with PHP namespaces, Composer support, 90% code coverage, and Travis-CI for automatic testing and releases.

While writing this Plugin, I settled on some WordPress coding conventions that I’d like to talk about.


One of the weirder things I read as a WordPress Plugin developer are tips such as “prefix all your function with name_” or “put all your functions in a class and declare them as static.” This advice is to prevent code collisions with the other 53,123+ Plugins available for WordPress. Big number.

On the other hand, Packagist lists 164,796+ PHP Composer packages, does not follow the aforementioned recommendations and has no such code collisions. Why? Because they use namespaces.

PHP Namespaces have been available since 2009. Other programming languages such as Java or Perl have had them for longer. WordPress Core doesn’t encourage PHP Namespaces but the syntax is fully supported.

If my class is a bunch of static methods and nothing else then I am doing it wrong. I should instead write a library of functions. If I’m afraid of function name collisions then I should use Namespaces because they solve that exact problem and they work fine with WordPress.

add_action( 'login_head', '\Kizu514\Coolname\this_works_fine' );
add_filter( 'login_headerurl', '\Kizu514\Coolname\welcome_to_php' );


Another odd thing I see while browsing OPP (other people’s plugins) are objects with “mostly” static methods.  There is some object-oriented approach to the design but most of the methods are static because they hook into actions and filters.

I think that an object in a WordPress Plugin should have, at most, two static methods. Every other method in a class should be public, protected or private.

There are very few cases where static methods are necessary. Most of the time public methods can be used. At worst, namespaced functions can invoke objects as needed and these concerns should be separate.

Here’s an example of what I mean (the code must also have PHPDoc comments  but for brevity, I have omitted these):

namespace Kizu514\CoolClass;

class Plugin {
	private static $instance = null;
	private $obj1;
	private $obj2;
	private $obj3;

	static public function init() {
		if ( is_null( self::$instance ) ) {
			$obj1 = new \Obj1();
			$obj2 = new \Obj2();
			$obj3 = new \Obj4( new \Obj3() );
			self::$instance = new self( $obj1, $obj2, $obj3 );
			self::hooks( self::$instance );
		return self::$instance;

	static public function hooks( Plugin $obj ) {
		add_action( 'save_post', [ $obj, 'doSomething' ] );
		add_filter( 'the_content', [ $obj, 'doSomethingElse' ] );

	public function __construct( $obj1, $obj2, $obj3 ) {
		$this->obj1 = $obj1;
		$this->obj2 = $obj2;
		$this->obj3 = $obj3;

	public function doSomething( $post_id ) { /**/ }

	public function doSomethingElse( $content) { /**/ }

Some time passes….

add_action( 'after_setup_theme', [ '\Kizu514\CoolClass\Plugin', 'init' ] );

The first static method, init, is hooked into one of many available launch points like plugins_loadedafter_setup_theme, or init. Because these actions happen before everything else a second static method, hooks, can do the rest of the work from inside the object itself.

Admittedly, even if I am down to just two static methods, they are gross. Glaring problems include “Singletons are evil” and not using Inversion of Control.

I’m very happy with this code style and I will be using it moving forward.

I just want a phone. Is that too much to ask?

Subtitle: How to disable Google Now Cards (that keep annoying you) when you swipe left (right? up? argh, fuck this shit!)

I own an Android phone.

In an effort to get rid of a feature that came with updates I’ve been going through dozens and dozens of settings. Unsuccessful, at wit’s end, writing angry loner feedback to Google support (also known as /dev/null) begging for them to make it easy for users to opt out of what I consider intrusive garbage when it turns out I can simply replace the launcher.

Google Now: Brought to you by a company that makes ~77% of its revenues from advertising, otherwise known as the “World’s most honest business model.”


KISS Android Launcher
Bonus feature: All my searches are now redirected to Wikipedia and/or DuckDuckGo.

KISS is a programming principle that stands for “Keep it simple, stupid!” The KISS Launcher code is GPL and available on GitHub. The Kiss Launcher app is available for free on Google Play.


Install Phalcon PHP On Windows 10

A common misconception is that you need a web server like IIS, Apache, or Nginx to get started with PHP7 development. In fact, PHP7 has its own built in web server that you can invoke at the command prompt. Many modern PHP frameworks support this, such as Phalcon PHP.

PHP7 and Composer on Windows 10

Installing Phalcon

Download the latest DLL file from GitHub and unzip to C:\PHP7\ext

Make sure the file you download matches your installed PHP version. For me, it was the non-thread safe version, so I picked a file that ended with

Add extension=php_phalcon.dll to your php.ini file

Drop to the command prompt and do:

php -v

If you get an error like “PHP Startup: Unable to load dynamic library…” that just means you installed the wrong version:

Whoops, I need x86 not x64.

Don’t panic, download another version, overwrite the DLL, and try again:

No news is good news.


Installing Phalcon Dev Tools

In a new folder create a bare bones composer.json file with only this in it:

    "require-dev": {
        "phalcon/devtools": "~3.2"

At the command prompt, cd to your folder, and do:

composer install

Create a simple project named my_project:

vendor\bin\phalcon.php.bat project my_project simple . 

Launch the built in web server:

cd my_project
..\vendor\bin\phalcon.php.bat serve


Switchers Guide To Windows 10 (For Web Developers)

I’m an OS X user from 2003 until 2011 and a Ubuntu user from 2012 until Windows 10.

The freedom to make irrational decisions.


Here are two (of many) options:

Install Git for Windows. Git for Windows provides a BASH emulator.

Install "Bash On Ubuntu on Windows"

Apt / Homebrew

Checkout Chocolatey or Scoop.

ALT + `

Install EasySwitch. Upvote this feature request in Feedback Hub.


Install Shut Up 10. Check out BleachBit.

Minimum Viable Toolset

Start Menu Shortcuts go in:

C:ProgramDataMicrosoftWindowsStart MenuPrograms*

Where is the `/etc/hosts` file?


Configure Notepad++ as Git editor

git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"


Are you a switcher too? Share your tips in the key party comments below.

Your Password Hashing Algorithm Is Bad And You Should Feel Bad


$pw = md5('password');
$pw = md5('salt' . 'password');
$pw = md5('complicated_salt' . 'password');
$pw = md5('complicated_salt' . strrev('password')); // Don't be clever.

Where md5() = sha1(), base64_encode(), etc.

This type of password hashing is still widespread and susceptible to rainbow table attacks.


$pw = password_hash('password', PASSWORD_DEFAULT);


Uses bcrypt, this particular implementation auto-magically hardens itself over time.

How to use

You are responsible for new \Pdo(), $condition, maybe asking the user to make their 'password' not suck. Read the snippet and reason about it. Don’t just copy/paste, it won’t work.

// Save user password into database

$pw = password_hash($_REQUEST['pw'], PASSWORD_DEFAULT);
$stmt = $pdo->prepare('UPDATE users SET password=? WHERE condition=?');
$stmt->execute([$pw, $condition]);

// Verify user login

$stmt = $pdo->prepare('SELECT password FROM users WHERE condition=?'); 
$row = $stmt->fetch();

if (password_verify($_REQUEST['pw'], $row['password'])) {
  // Check if PHP has improved password security for us
  if (password_needs_rehash($row['password'], PASSWORD_DEFAULT)) {
    // Fix password for next time
    $pw = password_hash($_REQUEST['pw'], PASSWORD_DEFAULT);
    $stmt = $pdo->prepare('UPDATE users SET password=? WHERE condition=?');
    $stmt->execute([$pw, $condition]);
  // Log in
} else {
  // Invalid password

Keep on shaking that salt shaker.

WordPress REST API Quickstart

The WordPress REST API has been available since 4.7.  It’s robust, consistent, and nifty to work with. Why? Backend and mobile developers can use other frameworks while still keeping WordPress around for their customers. Frontend developers can build sites using JavaScript without having to touch PHP. Up is down, left is right, dogs and cats living together… Let’s get started!

Recommended Tools


  • JSON Formatter: CTRL/CMD+Click a triangle to collapse/expand nodes at the same level.
  • YARC: When testing with Basic Authentication, make sure you are logged out of WordPress first.

Getting Started


WP API respects permissions but the developer must setup authentication separately.


WP API is self-documenting. Send an OPTIONS request to any endpoint and get back JSON Schema compatible info on how to use it:


To get the entire API schema in a single query, add context=help at the index. (Ie. http://site/wp-json?context=help )


WP API items have a _links node based on HAL (Hypertext Application Language):


To reduce the number of HTTP requests use the _embed parameter to tell the API that the response should include embeddable resources.


WP API exposes pagination info in the response header.



WP API renders JSON in a generic way that does not match the DB columns. Keep calm and RTFM:

if ( ! empty( $schema['properties']['author'] ) ) {
$data['author'] = (int) $post->post_author;
if ( ! empty( $schema['properties']['slug'] ) ) {
$data['slug'] = $post->post_name;
if ( ! empty( $schema['properties']['content'] ) ) {
$data['content'] = array(
'rendered'  => post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ),
'protected' => (bool) $post->post_password,

"author": 1,
"slug": "chapter-1",
"content": {
"rendered": "<p>Hello World!</p>",
"protected": false


Setup the Basic Authentication Plugin on your development environment.

In YARC, add your credentials:

YARC CredentialsSend an OPTIONS request to a post endpoint. The response will contain, among other information:

"methods": [
"title": {
"required": false,
"description": "The title for the object.",
"type": "object"

Translation: The API client can send a PUT request to change the title.

In YARC, send a PUT request with the following JSON to the endpoint:

"title": "My changed title!" 

Congratulations, you just changed the title. 

…cue the sound of a thousand keyboards furiously hacking.

Write Unit Tests For Your WordPress Plugin Using PhpStorm Code Completion

Git clone the WordPress develop repository somewhere on your hard drive:

git clone

Open wordpress-develop/tests/phpunit/includes/phpunit6-compat.php in a text editor.

PHPUnit version 5: Comment out the class_alias() functions in phpunit6-compat.php because these break PhpStorm code completion. (These files aren’t actually used by the testing framework, we only downloaded them so they could be included in the Project Configuration’s Include Path.)

PHPUnit version 6 and up: Do the same thing as PHPUnit 5, the paragraph above, except leave this line uncommented:

class_alias( 'PHPUnitFrameworkTestCase', 'PHPUnit_Framework_TestCase' );

In PhpStorm, go to: Settings -> Languages & Frameworks -> PHP and add wordpress-develop/tests/phpunit/includes to your Include Path.

Use WP-CLI to generate the tests scaffolding.

Write tests that extend WP_UnitTestCase. Look at the code in wordpress-develop/tests/phpunit/tests for examples.


Scrum Master (PSM-I) Certified

The Professional Scrum Master I assessment is a 60 minute time boxed test where you answer 80 multiple choice type questions. The passing score is 85%.

Last time, for my PSD I certification, I studied all by myself.

This time, I participated in a 2 day crash course given by agile coach Pawel Mysliwiec of Pyxis. The course was in French. It was much better than studying alone. It was fun to meet like minded Scrum practitioners.

I took the test April 9, 2017 and passed. My Score was 74 points (or 92.5%)

I now have two pieces of flair:

WordPress as a Development Platform

Many people dislike WordPress code. It’s no secret that for contemporary PHP developers WordPress feels antiquated. The founder of WordPress was even once-upon-a-time vocal about not keeping up to date with the PHP eco-system because reasons.

Times changed. So did PHP. So did WordPress.

To give credit where credit is due, the reasoning behind WordPress’ conservative change management is sound. They don’t want to mess with their insanely huge user base.

WordPress powers 30% of all websites on the internet.

That’s a lot of users. By choosing WordPress as your development platform you get massive traction for free.

But… that code. Ugh!

The good news is that when you develop for WordPress you don’t ever touch WordPress code. Instead you write a Plugin. [1] I put forward that in 2017 nothing is stopping you from writing a good, clean Plugin other than yourself.


WordPress is PHP 7 compatible. WordPress is also HHVM compatible [2]. Running on either vastly increases performance.

It follows that if your environment is PHP 7 then you get the syntax.


WordPress Plugins can have PSR compatible namespaces.

WordPress’ answer to Event Dispatcher (and/or Observer) are the add_action() and add_filter() functions. These functions are compatible with closures.

Meaning you can write code like:

add_action('init', function() use ($v) {
    (new \Acme\Foo\Bar\SomeClass($v))->someMethod();

add_action('init', '\Acme\some_function');

add_action('init', ['\Acme\Foo\Bar\SomeOtherClass', 'someStaticMethod']);

add_action('init', [$this, 'someOtherMethod']);

Or *any* standards compliant PHP 7 code you want to write.

With thousands of actions and filters available, pretty much any part of WordPress can be changed.


PHPStorm supports WordPress Plugin development out-of-the-box.

WP-CLI is a set of command-line tools for managing WordPress installations. It simplifies many developer and deployment related tasks and makes unit testing your plugin possible.

WordPress Plugins have PHP CodeSniffer rules ready to go.

WordPress Plugins can be installed using Composer.

Bedrock and Trellis for the win.


WordPress is licenced under the GPL. This still matters.

Getting Things Done

Is there room for improvement? Of course! Just like PHP, WordPress is always improving with the caveat that just like PHP, WordPress strives to keep backwards compatibly.

Developers rejoice, WordPress is moving forward, kicking and screaming as we drag it into the future.

[1] WordPress also has a REST API if you’re into that kind of thing…