Posts in Category: WordPress

Post to Post Links II WordPress plugin update

I’m starting a round of revisions for all my plugins, and creating screencasts for them. I’m also gradually moving plugin support over to the wordpress.org support forums (instead of using comment threads on posts here). The forum system has become very good over the years, and it just makes sense to have the discussions be part of the broader WordPress community. So if you have a support question for one of my plugins, please post it there.

First on the list of updates is my Post to Post Links II error: No post found with slug "post-to-post-links-wordpress-plugin", which makes it easy to link to other posts in your site. The new version has several new features. Here’s the overview from its readme file, and the screencast:

It lets you easily create a link to another post, page, tag, or category on your site. With a dialog form that uses autocomplete to look up posts by title, it’s very easy to find your link destination. The link will automatically use the title of the post, page, tag, or category as the link text, or you can supply your own link text.

It generates a shortcode instead of an HTML link. This means your links won’t break if you ever change your permalink structure, or change the organization of your categories.

You can also specify a named anchor for the link, and enter any additional attributes you need (such as an “id” or “name” for use with javascript or css).

It includes a button for the visual editor to launch the dialog form for looking up posts. If you prefer the HTML editor, you can install my Post to Post Links II error: No post found with slug "extensible-html-editor-buttons-wordpress-plugin", and Post-to-Post Links II will use it to register a button in the HTML editor button bar.

Dependency injection for WordPress plugins

In my last post, I criticized the use of the Singleton pattern in WordPress, and presented dependency injection as an alternative. But I presented it in only a very general way. Eric Mann provided detailed write-ups of how to use the Singleton pattern, so – to be fair – I should do the same with dependency injection (I don’t want to be a drive-by critic). See my last post for a general overview (and my slides below from my WordCamp Nashville presentation for a much deeper dive).

If your plugin is fairly simple – say a few hundreds lines of code – you don’t need to bother with dependency injection, or any other fancy design patterns. But when you get to the point where you have dozens of functions or methods, you’re feeling tempted to copy and paste code, and a little change here breaks something there, it’s time to get organized. The key to maintainable, flexible code entails understanding several concepts, but there are two which I believe are foundational:

  1. Writing small classes that do one thing (the single responsibility principle). I’ve written about this in detail in a previous post: WordPress plugins: does size matter? Applying the Single Responsiblity Principle
  2. Having your objects interact with each other through the use of dependency injection

In it’s simplest form, this means passing objects directly to each other, so they can make use each other’s functionality. Here’s a simple example of a button that can turn on and turn off a lamp:

class Button {
    private $lamp;

    public function __construct(Lamp $lamp) {
        $this->lamp = $lamp;
    }

    public function poll() {
        if (/* some condition */) {
            $this->lamp->turnOn();
        }

        //...
    }
}

This separation of concerns make it possible for a lamp to be passed to some other class to be used for other purposes (perhaps an electrical outlet), and it also allows for unit testing (a concept I won’t get into here). But we can do better. This button only works with lamps. What if we want to use it to control a motor too? We can create an SwitchableDevice interface and have our Motor class and our Lamp class implement it. Now the button can control anything that implements the SwitchableDevice interface:

class Button {
    private $switchableDevice;

    public function __construct(SwitchableDevice $switchableDevice) {
        $this->switchableDevice = $switchableDevice;
    }

    public function poll() {
        if (/* some condition */) {
            $this->switchableDevice->turnOn();
        }

        //...
    }
}

This may seem like a trite example, but the concept is very powerful. My Post to Post Links II error: No post found with slug "shashin-wordpress-plugin" plugin currently supports showing images and vidoes from Picasa, Youtube, and Twitpic. I can add support for any other photo or video service by creating a new subclass. For example, I could create a Flickr subclass that contains the logic particular to dealing with Flickr photos, just drop it into Shashin, and I’m done. I don’t have to monkey with any of the pre-existing code at all. The other objects in Shashin – for storing photo data, rendering the image tags, etc – don’t know and don’t care where the photo came from. As long as my Flickr subclass follows the same rules as the other subclasses, they know exactly what to do with it when they receive a Flickr photo object.

So what happens when you have objects that depend on other objects, that depend on other objects, and so on? You create an injection container to manage the dependencies, so that each individual object only needs to know about its immediate collaborators (that is, they know their friends, but they don’t get entangled with their friends’ friends). Injection containers allow you to follow the Law of Demeter (which I’ve written about previously here: Talking to strangers causes train wrecks). Here’s a simple example of what one looks like, from my Shashin plugin:

class ShashinContainer {
    // …
    public function getPhotoRefData() {
        if (!isset($this->photoRefData)) {
            $this->photoRefData = new ShashinPhotoRefData();
        }

        return $this->photoRefData;
    }

    public function getClonablePhoto() {
        if (!isset($this->clonablePhoto)) {
            $this->getPhotoRefData();
            $this->clonablePhoto = new ShashinPhoto($this->photoRefData);
        }

        return $this->clonablePhoto;
    }

    //...
}

If another class needs a clonablePhoto, it can ask for it from the container, and not have to worry about what dependencies the clonablePhoto has. Again, this is very powerful: if you get a new business requirement that entails a major structural change, you can handle it without having to sift through your entire codebase. You can make the changes to the classes that are directly affected, with a minimal ripple effect on the rest of your code.

This illustrates more specifically how dependency injection can be used as an alternative to the Singelton pattern, for instantiating objects only once when you don’t need more than one. In my injection container example, you’ll see the objects are stored as properties of the container, and are never created more than one time. The limitation is that an unknowing programmer could bypass the container and create more instances of the objects by directly calling “new” on its class. This limitation is something you need to weigh against the various shortcomings of using Singletons (see my previous post).

Mike Schinkel uses the Singleton pattern for another purpose – to avoid having the instance of a plugin’s class in the global namespace. I’m not sure how much this solution helps with the overall problem: other developers trying to deal with your plugin still need to know how to find it – they’re just looking for something else now, and have to learn this particular Singleton implementation (however I have not yet had to deal with this problem in my own work, so I may be overlooking some aspect). Based on the comments on his post, it seems like the main frustration developers have is figuring out where the hooks and filters are in someone else’s heavily object oriented plugin (where the logic can get spread out). This strikes me more as a code organization problem, not a variable scoping problem. In my plugins, I put almost all my hooks and filters in one place. This is the main method for my Shashin plugin:

public function run() {
    add_action('admin_init', array($this, 'runtimeUpgrade'));
    add_action('admin_menu', array($this, 'initToolsMenu'));
    add_action('admin_menu', array($this, 'initSettingsMenu'));
    add_action('wp_enqueue_scripts', array($this, 'displayPublicHeadTags'));
    add_shortcode('shashin', array($this, 'handleShortcode'));
    add_action('wp_ajax_nopriv_displayAlbumPhotos', array($this, 'ajaxDisplayAlbumPhotos'));
    add_action('wp_ajax_displayAlbumPhotos', array($this, 'ajaxDisplayAlbumPhotos'));
    add_filter('media_upload_tabs', array($this, 'addMediaMenuTabs'));

    // ... and so on - there are 8 more...
}

This makes things pretty easy to find. It’s through the method calls listed here that Shashin’s other objects get instantiated. There’s really no need to put these calls anywhere else. They are all stand-alone actions in the WordPress environment, and kick off everything else that happens in my plugin.

If you’ve gotten this far and still want more, here are my slides from my WordCamp Nashville presentation on dependency injection, which go into more detail on the examples I used above. There are also more advanced examples, and an overview of class autoloading:

Dependency Injection for WordPress from mtoppa

The case against Singletons in WordPress

Eric Mann wrote a thoughtful and detailed argument for using the Singleton pattern in WordPress development. Given the particular nature of the WordPress development environment, his reasoning is understandable and clearly comes from experience. The criticisms I’ve seen so far in his post comments, and in Hacker News, don’t make good counter-arguments. They are coming from people who either aren’t familiar with the constraints of developing in WordPress, or who are just looking for any opportunity to bash PHP developers.

…So here comes the “but:” I think he’s made a very valuable contribution to the discussion of code design in WordPress, but I don’t agree with his conclusions. I have a few reasons:

1. WordPress is positively bursting at the seams with global state. This is a huge design sin, but a forgivable one, given that WordPress came of age before PHP had a decent object model. However, Eric defends it, arguing in response to a comment that:

PHP applications like WordPress are written in a single-threaded, request-response pattern. Having a global scope is useful, and having instantiated singletons available in that scope is also useful.

I don’t find this persuasive. The vast majority of web applications, written in a variety of languages, are single threaded and follow a request-response pattern (given how HTTP works). That doesn’t make dumping stuff in global scope ok somehow. I won’t go on at length about the evils of globals – it’s been discussed thoroughly by many, and avoiding them is considered axiomatic to good design. A good place to start is Misko Hevery’s Google talk on Global State and Singletons. His examples are in Java, but PHP 5’s object model is very similar, and the examples he provides aren’t all that different from the challenges of working in WordPress.

2. The Singleton pattern doesn’t isolate you from global state. As Misko Hevery explains in his talk, that global state is actually transitive to everything within the Singleton object. Eric outlines some steps to get around that for the sake of unit testing. He asserts that the unit testing difficulties are the only significant problem with the Singleton pattern. But the testing problems are symptomatic of it simply being a bad design pattern. It’s the “S” in PHP expert Anthony Ferrara‘s collection of STUPID anti-patterns (that’s a slideshow, so use your arrow keys to see the bullet points). In Eric’s follow-up post, he’s Asking WordPress developers to create their own Singleton classes by deriving a class from an abstract class, that is in turn derived from an interface. This is a heavy lift for a solution that at the end of the day leaves you right where you started with global state.

3. Eric rejects dependency injection as an alternative by giving an overly simplistic presentation of what it has to offer (I gave a talk on dependency injection at WordCamp Nashville last year). A dependency injection solution can meet all but one of his goals, and lets you do some real, unshackled OO programming. What’s needed is an injection container. A container knows what objects are needed to build other objects, and hands you the object you want when you ask for it. So your calling code never invokes “new” for an object it wants – it simply asks the container to deliver it. The beauty is that objects only need to know how to talk to their immediate collaborators, and the container takes care of the composition (e.g. A House just knows it needs a Door, it doesn’t need to worry about the DoorKnob or the Deadbolt). Now here’s the thing – you can program your container to know whether it should give you a fresh new instance of the object requested, or whether to keep a single instance of that object in memory, and deliver that object when asked for it (like Eric’s WP_Session object).

Here’s a simple example from my Shashin plugin, which displays photos from Picasa, Twitpic, etc:

class ShashinContainer {
//...

    public function getClonablePhoto() {
        if (!isset($this->clonablePhoto)) {
            $this->getDatabaseFacade();
            $this->clonablePhoto = new ShashinPhoto($this->dbFacade);
        }

        return $this->clonablePhoto;
    }

// ...
}

There are a couple things going on here:

  • The container takes care of the composition: it knows that a clonablePhoto needs a dbFacade. The caller doesn’t need to know or care. This approach is very liberating in terms of keeping your system open to future design changes (i.e. composition changes are localized to the container, minimizing the risk of change on the rest of the system).
  • After creating the clonablePhoto, the container object keeps it around as a property. If a caller asks for a clonablePhoto again, it simply sends the same clonablePhoto (in this case it’s an immutable object, so there’s no reason to bother instantiating more than one).

I mentioned this gives Eric all but one thing he wants, and that is the one overriding thing he wants, which drove him to the Singleton pattern: an absolute guarantee that no one can ever, ever create more than one WP_Session object.

How you feel about that depends on what you think is reasonable to expect from people who contribute to WordPress core development. The Singleton pattern is a least common denominator kind of solution – that our choices for design patterns are bounded by what the least capable WordPress code contributor can handle. I prefer to set my sights higher. There are already a whole host of expectations in terms of the security of code that’s contributed, how it conforms to WordPress coding conventions, and its overall quality. I don’t think it’s unreasonable to expect a basic understanding of OO design principles.

Each new version of WordPress adds features, and therefore complexity, to the codebase. My concern is that, with all its global state, the WordPress development process will become ever more arcane and complex: the necessary sequence of operations and the number of simultaneous dependences will likely become overwhelming at some point. Right now that’s mitigated by the fact that the core team is incredibly talented, and there’s a huge pool of people available and eager to spot bugs, contribute fixes, etc. Evolving the codebase to a place where it eventually doesn’t rely on global state will allow the codebase to become more modular and flexible, streamline the development process, and ultimately allow WordPress to keep pace with the ever growing list of things people want it to do.

The transition steps don’t have to be painful, and can be undertaken incrementally:

  • WordPress’ custom hooks and functions will need to stay available as they exist now, for backwards compatibility, but the code in them should be migrated over time, until eventually all those functions are just wrappers for calls to object methods.
  • Put all the WordPress classes that already exist behind injection containers. That hides all the global state, and therefore allows a flexible, OO composition approach to grow and take hold. Then in the long term it allows that global state to be eliminated through incremental redesign. In the end you’d have a main WordPress class that would be instantiated to do all the high-level calls needed to kick things off. Once global state is eliminated, the fun can really begin. For example, with a little extra configuration, you could run multiple simultaneous instances of WordPress from a single codebase.
  • Once the injection containers are in place, code that’s contributed to core should never contain the keywords “global” or “new” (except inside injection containers). I think that’s a pretty simple rule to communicate.

At its heart, object oriented design is really about encapsulation and messaging (the exact opposite of design that relies on global state). It wasn’t created to make someone in an ivory tower happy – it exists to solve the inevitable problems that arise in complex software, and is the child of decades of hard-won experience from many talented people. It’s when you make the leap to understanding this composition approach to design that the benefits really kick in. As explained in the book Growing Object Oriented Software, Guided by Tests:

An object oriented system is a web of collaborating objects… The behavior of the system is an emergent property of the composition of the objects – the choice of objects and how they are connected… Thinking of a system in terms of its dynamic communication structure is a significant mental shift from the static classification that most of us learn when being introduced to objects.

The WordPress codebase has grown to a point of sufficient size and complexity that I believe it will substantially benefit by starting an evolution towards this design paradigm.

Handling WordPress meta data and post revisions

I’ve worked with WordPress post meta data and meta boxes extensively in the past, but it’s been a while, and I’m using them in a current project, so I looked online for a refresher. There’s a lot of information out there, and a lot of it is either way out of date or way out of whack in terms of best practices. The best introduction I found was How to Create Custom WordPress Write/Meta Boxes at wptuts.com. It covers all the basics, but there’s a more advanced aspect I want to cover here, which is managing meta data with post revisions (the following was written for wordpress.com blogs, but applies to WordPress in general):

Each time you click Save Draft or Update, a revision is saved… Revisions allow you to look back at the recent changes you’ve made and revert to an earlier version if necessary.

If you are simply adding or replacing meta data for a post when you save it, then you don’t need to worry about post revisions: your meta data will get attached to the published version of the post. But if you need to, for example, add a value to an existing serialized array of meta data, you need to check for and handle post revisions.

If you are taking the input from your meta box and adding it to an existing array of meta data, you’ll want to make sure you retrieve the meta data that’s attached to the published post, as WordPress saves the revisions as child posts of the parent published post. Here’s an example callback for the save_post action:

function your_save_meta_data_function($post_id) {
    // standard status and security checks
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!isset( $_POST['meta_box_nonce']) || !wp_verify_nonce($_POST['meta_box_nonce'], 'your_meta_box_nonce')) return;
    if (!current_user_can('edit_post')) return;

    // if we need to augment existing meta data,
    // we need to make sure to retrieve it from the parent post
    if ($parent_id = wp_is_post_revision($post_id)) {
        $your_meta_array = get_post_meta($parent_id, 'your_meta_array', true);
    }
    else {
        $your_meta_array = get_post_meta($post_id, 'your_meta_array', true);
    }

    // make sure your user input is safe 
    $your_new_value = sanitize_text_field($_POST['your_new_value']);

    // if there are previously saved meta values, initialize an array
    // as otherwise $your_meta_array will be an empty string
    $your_meta_array = empty($your_meta_array) ? array() : $your_meta_array;
    $your_meta_array[] = $your_new_value;
    update_post_meta($post_id, 'your_meta_array', $your_meta_array);
}

The AUTOSAVE check blocks the function from executing for automatic saves, but if you click “save draft,” this comes into play (and, interestingly, when you click “publish” as well, because your callback actually gets called twice by save_post). Also, if you’re wondering where the array serialization happens, WordPress does it for you.

There are other ways you could approach this particular problem (like passing all the array values through the form, but that’s just another kind of ugly, and may not be very practical if its a nested array). But you’ll also want to check post revision status if you’re doing something like firing off emails to people, or anything else that shouldn’t happen when just saving a revision.

WordCamp New York City 2012

WordCamp NYC 2012 kickoffWordCamp NYC 2012 kickoff
WordCamp NYC 2012 kickoff09-Jun-2012 09:13, Canon Canon PowerShot SD780 IS, 3.2, 5.9mm, 0.04 sec, ISO 400
 

With 12 session tracks on Saturday, followed by unconference sessions on Sunday and encore performances of Saturday’s most popular presentations, WordCamp NYC last week was by far the biggest WordCamp I’ve attended. Then of course there’s the real reason people go – the after party on Saturday (there was also the sponsors and speakers party on Friday, which was a lot of fun too). At the parties I got to do what years of social training had previously convinced me was unacceptable: discuss code while drinking beer. I got to chat for a while with @garthkoyle (from Event Espresso), @jason_coleman (of Paid Memberships Pro fame), @vidluther (from zippykid), and @tinakesova (from Siteground).

Brad Williams speaking on WordPress security at WordCamp NYCBrad Williams speaking on WordPress security at WordCamp NYC
Brad Williams speaking on WordPress security at WordCamp NYC09-Jun-2012 09:37, Canon Canon PowerShot SD780 IS, 5.8, 17.9mm, 0.05 sec, ISO 640
My WordCamp NYC presentation on object oriented programming for WordPress pluginsMy WordCamp NYC presentation on object oriented programming for WordPress plugins
My WordCamp NYC presentation on object oriented programming for WordPress plugins
 

My presentation was on object oriented programming for WordPress plugins (my slides are below). I decided to focus on OOP in general with PHP, as its simply a huge topic to try to cover in 30-40 minutes. The room was full and there were good questions at the end, so it went well. I was 1 of 3 presenters from WebDevStudios – Brad presented on WordPress security, and Eric on the rewrite API.

WebDevStudios WordCamp NYC dinnerWebDevStudios WordCamp NYC dinner
WebDevStudios WordCamp NYC dinner
 

Brad treated us to a great dinner afterwards (ribs!) and I stayed up too late with the WebDevStudios team Saturday night (including honorary team member for a night, Captin Shmit – yes that’s how he spells it). I found out at 2AM (when I checked the conference web site after we got back to the hotel) that the unconference presentation submission I made earlier in the day had been scheduled for Sunday morning.

Whiteboard from my WordCamp NYC unconference session on Agile project managementWhiteboard from my WordCamp NYC unconference session on Agile project management
Whiteboard from my WordCamp NYC unconference session on Agile project management
 

So on my way back to the conference Sunday morning I stopped at CVS to get post-it notes and dry erase markers, for doing an Agile project management workshop. Aside from scribbling some notes 20 minutes before the session started, I didn’t have a detailed plan, and it turned out to be a lot of fun. My session was right before lunch, which turned out to be great, as almost everyone stayed after the time was up, and we went for another half hour. I started the session by having everyone describe their client relationship and software development problems (in brief post-it note format) and collected those on one side of the white board. Then I had them describe the things they want to achieve in their business (also in post-it note form), and collected those on the other side of the board. Then we spent about an hour talking through how to get from one side of the board to the other. It was only enough time to scratch the surface of Agile practices, but what made the biggest impression on everyone is how almost all software development teams face the same challenges, and that there are ways to deal with them that are concrete, achievable, and rewarding. ContentRobot selected it as one of the best sessions.

To continue with the shameless self-promotion, here are some tweets about my talks:

Tweets about my WordCamp NYC presentations
Tweets about my WordCamp NYC presentations
 

And here are the slides from my OOP talk (the last half of the slideshow contains my slide notes).

If you want to see more, check out the WordCamp NYC 2012 site and ChrisDigital has a collection of links to other summaries, and slides.

WordCamp Nashville

People arriving for the start of WordCamp Nashville, at Watkins CollegePeople arriving for the start of WordCamp Nashville, at Watkins College
People arriving for the start of WordCamp Nashville, at Watkins College21-Apr-2012 09:55, Canon Canon PowerShot SD780 IS, 3.2, 5.9mm, 0.033 sec, ISO 320
My dependency injection talk at WordCamp Nashville (photo by Patricia Melton)My dependency injection talk at WordCamp Nashville (photo by Patricia Melton)
My dependency injection talk at WordCamp Nashville (photo by Patricia Melton)21-Apr-2012 00:56, Canon Canon EOS 40D, 4.0, 70.0mm, 0.017 sec, ISO 1600
@rfair presenting "Less, JS, and WP"@rfair presenting "Less, JS, and WP"
@rfair presenting "Less, JS, and WP"21-Apr-2012 16:07, Canon Canon PowerShot SD780 IS, 3.2, 5.9mm, 0.04 sec, ISO 400
 
The Otto and Nacin show - @otto42 @nacinThe Otto and Nacin show - @otto42 @nacin
The Otto and Nacin show - @otto42 @nacin21-Apr-2012 12:09, Canon Canon PowerShot SD780 IS, 3.2, 5.9mm, 0.033 sec, ISO 250
@ryngrn presenting "Child Theme Frameworks"@ryngrn presenting "Child Theme Frameworks"
@ryngrn presenting "Child Theme Frameworks"21-Apr-2012 11:06, Canon Canon PowerShot SD780 IS, 3.2, 5.9mm, 0.033 sec, ISO 400
@studionashvegas presenting "The Blank Screen: Overcoming Fear of Pressing from Scratch"@studionashvegas presenting "The Blank Screen: Overcoming Fear of Pressing from Scratch"
@studionashvegas presenting "The Blank Screen: Overcoming Fear of Pressing from Scratch"21-Apr-2012 10:11, Canon Canon PowerShot SD780 IS, 3.2, 5.9mm, 0.025 sec, ISO 400
 

I’ve traveled coast-to-coast across the US 4 times, but until this past weekend I had never been in the South (except for a brief visit to UVA many years ago). I was in Nashville for only 48 hours, and I enjoyed every minute of it. The first thing I noticed was how kind and polite everyone is. The driver of my shuttle bus from the airport pointed out all the sights as we drove into town, and he seemed genuinely interested in what everyone on the bus was planning to do that weekend. I spent the day on Friday with my friend Caryn, who I hadn’t seen since we finished grad school 16 years ago. She showed me around town, and it was great to catch up.

This was Nashville’s first WordCamp. The organizers did a great job pulling it together, and they clearly had a lot of local talent to draw upon for their speakers. Coming from Philly, I think I was the only Yankee among the speakers – I felt honored to be included (Nacin, coming from DC, is a borderline case 😉 ).

I was in the developers’ track all day. The first two sessions were design focused, and here’s an excellent summary of both presentations. They were followed by the Otto and Nacin show. They are both deeply involved in the development of WordPress, and they gave a preview of features in WordPress 3.4. Their talk was the most popular of the day in the developers’ track.

I was up next after lunch, and my talk went well. It was an advanced topic (dependency injection) so I drew a smaller crowd. But I got some good questions towards the end, and some good tweets:

@rfair's tweet about my session
@rfair's tweet about my session29-Apr-2012 19:40
 

Here is a non-technical summary of my talk.

Russell Fair wrapped up the day, and he did a great job of sharing his experiences using LESS with WordPress.

I didn’t get to see Joel Norris’ WordPress bootcamp presentation, but from what everyone was saying, I believe he gets the prize for having the most popular session. He stayed in character as a drill sergeant for almost the entire session. And he was in costume – here’s a photo.

The speakers dinner and the after party were both a lot of fun. I learned a lot chatting with Otto and Nacin, made some new friends, and my friend Caryn was able to come too, so it was a great evening.

If you want to read more, WP Candy has a great review, and they also have links to many of the presenters’ slides. There’s also a great photo pool on Flickr. Here are my slides:

Shashin 3.1.3, and why all the recent changes

Update: Shashin 3.1.4 takes care of the activation issue – you no longer need to click the “deactivate” and “activate” links in the plugin panel when upgrading.


I’ve uploaded Shashin 3.1.3 to wordpress.org. Several people have complained of error messages that start with “Invalid data property __get for…” when updating to 3.1.x. These messages relate to new settings that are added during activation, but they were not actually being added. This puzzled me because the WordPress automatic updater shows a message saying it is deactivating and reactivating the plugin when it upgrades. The problem is, it’s not actually doing it – here is the WordPress defect ticket: Auto update plugins does not activate activation hooks.

Apparently this behavior is an intentional choice. I’ve submitted a patch that corrects the wording (so at the very least, plugin authors like me don’t misunderstand what it means). In the future I will make sure to work around this, but with 3.1.3, you will need to deactivate and reactivate Shashin one more time yourself from the plugin menu after upgrading.

My apologies if you’ve had other difficulties with the recent Fancybox changes. I’ve included Highslide with Shashin since 2008, and I gradually added features and made improvements as I learned the capabilities and quirks of Highslide. Due to a licensing conflict I was alerted to, I had to rip Highslide out of Shashin immediately and switch to a different viewer with a GPL compatible license (Shashin was temporarily removed from the wordpress.org plugin repository because of this). Some of the other great viewers, like PrettyPhoto, are also not GPL compatible, so I went with Fancybox. I had only a short period of time to add it, and I’ve spent many hours recently working through some of the intricate issues involved with making it work with Shashin.

Version 3.1.3 makes the following improvements:

  • Added automatic timed slideshows
  • Improved captions for photos shown after clicking an album thumbnail (this also fixes the bug with then “return” link for albums)
  • In FancyBox caption, show exif data if requested, even if there is no photo caption text
  • Bug fix: show correct FancyBox captions on photos shown after clicking an album thumbnail, on pages that have a mix of photo groups and album thumbnails
  • Possible bug fix: add a 30 second buffer to the time check when synchronizing albums, in case there is a delay between synchronizing the album’s meta data and the album’s photos (this is to try addressing occasional reports of photo ID numbers changing, which means they are being deleted and re-added).

Also, its worth highlighting that in 3.1.2 I resolved the problem of the Fancybox slideshow navigation controls overlaying controls for videos. The video controls are accessible now.

Shashin 3.1, with Fancybox

Update 3/9: I’ve uploaded version 3.1.2 of Shashin, which makes two improvements: the code for handling the FancyBox captions is now cleaner (no HTML embedded in the title attribute) and the navigation controls in slideshows now don’t overlay controls for videos (so you can use the video controls now).

Update 3/7: I’ve uploaded new versions of Shashin and Toppa Plugin Libraries that corrects the installation bug in Shashin 3.1 that was affecting new installations. You will need to update both plugins.


Shashin 3.1 is now available for download at wordpress.org. I’ve added support for WordPress multi-site installation, and improved error reporting when there are problems with album synchronization. But the biggest change is that, due to a licensing conflict, I have removed Highslide and replaced it with Fancybox 1.3.4. Highslide uses a Creative Commons license, which is not compatible with the GPL, and all code in the wordpress.org plugin repository must be GPL compatible.

While the visual style of Fancybox is different from Highslide, the functionality is mostly the same. However, there are a few limitations with Fancybox:

  • Loading Twitpic photos may be slow. Twitpic URLs for photos redirect to cloudfront.net, and Fancybox is unable to resolve redirects. I added my own code that resolves the redirect before passing the link to Fancybox, but this means two calls for loading every photo.
  • Fancybox requires this approach to the code when mixing videos in groups with photos, and this approach if you want to dynamically set the dimensions of a video, and the two are not compatible. I decided including videos in groups was more important, so video dimensions are fixed for all videos (you can set your desired video size in the Shashin settings page).
  • A related issue is that the Fancybox overlay for navigating videos in groups overlaps the video controls, which means you can’t pause, adjust volume, etc with videos if they are in groups. This is simply an unfortunate limitation of Fancybox. As of Shashin 3.1.2 this is no longer a problem.

So why Fancybox? Despite these issues it is still one of the more robust viewers available, and it is GPL compliant. Highslide, PrettyPhoto, and even the just released version of Fancybox (2.0) all use GPL incompatible Creative Commons licenses.

Making the transition to Fancybox was a huge effort. I’ll be willing to entertain including another GPL compatible viewer if you can recommend one that doesn’t have these technical limitations, but not right now 😉

Toppa Plugin Libraries 1.2 simplifies making plugins compatible with WordPress multi-site

In my new position at WebDevStudios, I’m wading deep into the world of WordPress multi-site functionality. In version 1.2 of Toppa Plugin Libraries, there’s a new method which makes it easy for plugin authors to make their plugins WordPress multi-site compatible. It is based on the excellent code Shibashake made available for doing this. I took that articles’s 3 separate (but almost identical) functions for activating, deactivating, and uninstalling a plugin, and abstracted them into a single method. Why? Because “duplicate code is the root of all evil in software design.”

As a plugin author, all you need to do is write your activation or deactivation function as you normally would, and then:

$functionsFacade = new ToppaFunctionsFacadeWp();
$functionsFacade->callFunctionForNetworkSites('yourActivationFunction');

This will call your activation (or deactivation) function for every site in the network, including the parent site.

Or in an object context, after passing the FunctionsFacade to your object:

$this->functionsFacade->callFunctionForNetworkSites(array($this, 'yourActivationMethod'));

For uninstalling, you need to pass a 2nd argument, which indicates that the “networkwide” flag should not be checked (for some reason, WordPress multisite uses this flag for activating and deactivating plugins, but not for uninstalling).

$this->functionsFacade->callFunctionForNetworkSites(array($this, 'yourUninstallMethod'), false);

I’m going to release the next version of Shashin soon, which uses this method to make it multi-site compatible, so I wanted to get this Toppa Plugin Libaries release out first. Enjoy!

WordPress plugins: does size matter? Applying the Single Responsiblity Principle

In the last episode of WP Late Night, there was a brief debate about plugin size. Ryan expressed a preference for smaller plugins with tightly focused functionality. It’s natural to worry that, as the number of lines of code increases, so does the likelihood of bugs, and performance slowdowns.

This concern makes sense if you’re assuming plugin code is not very well organized and not very well tested. Unfortunately, that’s a safe assumption with many plugins. As plugin authors, we should have higher standards for our work. There are two things that come to mind:

  1. Optimizing the readability and maintainability of our code. This means writing “clean code” (the subject of my Philly WordCamp presentation). It reduces the likelihood of bugs, and makes our plugins easier to enhance and adapt to changing needs. It also makes it more likely that others will contribute to the project, or learn from it, and start writing better plugins themselves. These are some one of the main attractions for participating in the WordPress open source community, right?
  2. Optimizing for performance: one aspect of the “clean code” philosophy is to not prematurely optimize code for performance, especially when our guesses about how to do that are often wrong.

    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason – including blind stupidity.

    Wulf, W. A. “A Case Against the GOTO,” Proceedings of the 25th National ACM Conference, August 1972, pp. 791-97.

The rule of thumb is to optimize for readability and maintainability first. If a performance problem comes up, it is likely stemming from a small area of the code, and you can focus your performance optimization efforts there. As one person put it: “There is far, far more money wasted on fixing and customizing and maintaining hard-to-read code than there is lost on inefficient code.”

There are many techniques involved with writing clean code. A foundational one is following the Single Responsibility Principle (SRP). Bob Martin has a very succinct definition of the SRP: “a class should have only one reason to change.” In his book Agile Software Development, he explains further:

If a class has more than one responsibility [more than one reason to change], then the responsibilities become coupled. Changes to one responsibility may impair or inhibit the ability of the class to meet the others. This kind of coupling leads to fragile designs that break in unexpected ways when changed.

If you follow the SRP, then it doesn’t matter how big your plugin is. What matters is how you use it.

The trick, of course, is figuring out what it means to have a single responsibility. WordPress itself helps you figure this out. When you call a WordPress hook or filter, it’s likely that you will want to create a class that implements what you intend to do for that hook or filter call. For example, if you call add_shortcode, then you should have it instantiate a class that implements your shortcode. If that class needs to change, it will be only because your needs for the shortcode have changed. The shortcode logic is not tightly coupled to other parts of the code. Removing that coupling is an important step towards also removing that sinking feeling of fear when you start monkeying with the innards of some gigantic application.

Not every hook and filter call deserves its own class. Some are merely stepping stones to others and do not need their own class. For example, if you call admin_menu simply for the sake of calling add_options_page, one class is enough. Others may need more than one class to support them. But for getting your feet wet, having a class per hook or filter is a good place to start.

My Post to Post Links II error: No post found with slug "shashin-wordpress-plugin" has a total of 55 classes and subclasses (you can see the code on GitHub). How can you find what you’re looking for in all those classes? It sounds horribly bloated for a WordPress plugin, right? It’s actually the opposite.

A coding habit that goes hand in hand with the SRP is the use of meaningful names. Each class in Shashin serves a specific purpose, and has a name that tells me what it does. If I need to make a change to the settings, I go to the Settings class; if I need to make a change to how album synchronizing is done with Picasa, I go to the PicasaSynchronizer class, etc. The majority of the classes are less than a couple hundred lines. With small, well-named classes and methods with clear purposes, when there is a bug, it’s usually not hard to find. And if I need to change something, I can make that change in one place with a greatly reduced fear of breaking something unrelated.

By using a class autoloader, such as Post to Post Links II error: No post found with slug "toppa-plugin-libraries-for-wordpress", you can also save yourself the trouble of figuring out where to put require_once statements, for loading your class files. With an autoloader, a class file is loaded only when “new” is called (so if you are worrying about performance with so many objects, they are only loaded when they are actually needed). How you keep track of object dependencies, and when and how you instantiate your classes, are what I’ll write about in my next post, which will cover using an injection container.

%d bloggers like this: