What is the Dependency Injection Container (DIC)?

If you’re coding for the web, you almost certainly have encountered frameworks that make use of the Dependency Injection Container. Incredibly useful – but what is it?

In the most simplistic way – it’s just a great big bag of stuff. That’s it. There’s nothing magical about the container, it’s simply an object that stores references to other objects. Combined with a liberal use of Interfaces, this allows for a high level of abstraction and therefore also aids in unit testing smaller code parts.

For example, if you’re injecting the entire DIC into a component, you are metaphorically handing that component a great big bag of stuff and saying “here’s what we have to work with. Ask for it by name.” The component may then access the container and all configured dependencies.

You may well now be saying “well that sounds a bit like code soup” – and you’d be right. Normally, you’d only inject the dependencies that a component requires (and not the whole bag). The major frameworks (e.g. Laravel, Symfony, Zend) feature Dependency Injection Containers and an associated service locator and dependency manager. These are no longer simply “great big bags of stuff“, but true DI systems that allow for a high level of abstraction.

For a super simple Dependency Injection Container, see Pimple (by Sensio Labs). This is a great place to get started with understanding how a system will utilise a DIC. It is super simple, and forces you to understand how things are bootstrapped and provided for your system.

For more detailed information on dependency injection, see these links:

Features image (with modifications):
Coffee Bag W” by DaveBleasdale. Licensed under CC BY 2.0

Remove extra RSS feeds in WordPress

Here’s a WordPress snippet to remove RSS feeds for comments while keeping the main one available.

RSS Icon

RSS is super nifty. It’s a great way to keep on top of breaking news and articles from your favourite blogs and/or aggregators (I’ve got over 100 subscriptions in my feedly reader).

So it’s a wonder then that WordPress offers RSS feeds for comments on all your posts. I presume there’s a group of people who really like to track conversations, but in my experience, it’s the minority. This functionality should really be an additional (and not core) part of WordPress. If you want to prevent your site serving pointless additional RSS feeds, you’ll need to remove them from wp_head.

Removing them, however, is a two-step process. Add the following to your functions.php file:

And that’s it. The first two actions strip the RSS using remove_action with a high priority. The final add_action call tells WordPress to load our function when processing wp_head. This will go through and reinsert the main feed, leaving the comment feed out.

Congratulations! Your post conversations are now untrackable.

WordPress: Add page slug to body class (including parents!)

Are you using WordPress as a CMS? Do you want to style pages with CSS logically? You might want to try this.

By default, WordPress will inject the page and its ID into the body class. That’s great if you’re only running a single install, or if you really really don’t care what your CSS looks like.

Let’s face it – you care. Otherwise, you wouldn’t be here. Here’s a snippet that will inject the current page’s slug and all slugs of its parents into the body class of your HTML.

Add this to functions.php

And that’s it! You can then start chaining together page classes to target little overrides that your clients are probably hassling you about.

Help! register_activation_hook isn’t working!

If you’re developing a plugin, chances are you’ve been caught out by the WordPress activation/deactivation hooks.

I’ve been working on an Instagram plugin for WordPress, and in doing so have needed to use the functions register_activation_hook and register_deactivation_hook.

However, I – like many others, it seems – can’t get the hooked functions to execute. They simply don’t fire. To illustrate the problem, here’s an example from the code:

I would fully expect the system to execute the functions hooked within the constructor. Had that been the case, I wouldn’t have lost a day debugging a non-existant problem.

Finding a solution

Of course, everyone’s setup is different. There were many suggestions for fixing the problem. For the sake of usefulness, here’s the other major suggestion:

Your global variables aren’t global

If (like me), your plugin is a global, you actually need to explicitly define it as such with the global keyword. For example, the snippet

should instead by written this way:

Why? Well, for this, we need to consider how the plugin has its code loaded. After installation, your plugin has its code included “normally” with standard includes. This creates the global scope that you would expect. However, when you register a function with register_(de)activation_hook, it is called from within another function’s scope, effectively hiding your non-explicit globals.

Confused? Consider the plugin example from earlier. The variable $my_instagram is declared in the global scope, with global visibility. When your code executes, your plugin is included at the same scope, meaning you will have access to the variable (as they share the same suitably-high scope). Due to the way the hook/filter system in WordPress works, your activation/deactivation hooks are executed within a localised (not global) scope.

Screen beans - the only thing worse than scope.
Screen beans – the only thing worse than scope.

This scope-confusion applies to all functions created using create_function, or (in our specific example), functions called with call_user_func (and call_user_func_array). These functions have their own scope and are thus shielded from the cheap-and-nasty pile of implicit “globals” that haven’t been properly declared as such.

You can find a suitably more technical (and probably correct) write-up at the WordPress Codex page for register_activation_hook.

tl;dr: Explicitly declare your globals if you want them to work everywhere.

Ok, that’s great, but what’s the answer?

After having accidentally (and rather unwillingly) been given a very rough refresher on scope, I found that this was not my problem at all. Even running proxy functions (which eliminates scope issues) failed to call the functions specified in the hook.

After much trial and error (and I mean much), I found that the paths within register_(de)activation_hook were not matching the path found in plugin_dir_path. In fact, __FILE__ was returning a completely different path.

The problem? I had symlinked the theme directory in my install, meaning that __FILE__ returned a different path to plugin_dir_path. This is especially important, as the file path specified by the first parameter of register_(de)activation_hook is included before the function specified by the second parameter is called. So, if the path in the first parameter is wrong, you probably aren’t going to be executing many functions today.

The Fix

This is always my favourite part. To fix the symlinking problem, you just have to be very specific when you’re asking WordPress to execute a hook for you.

Fixing the first example, we get:

The most important changes occur on lines 1, 16, and 17. The first line fixes the definition by manually specifying the path using the base plugin directory (instead of an automagic WordPress search). Lines 16 and 17 specify the main plugin file itself as the path (instead of relying on __FILE__).

This allowed WordPress to find the plugin files without a hitch, which is especially important in the installation/uninstallation phases.

Moral of the story? Check your paths first.

Paths

Pink Ribbon Breakfast

I don’t normally plug work that I do in my daily grind, but this one is for super-great cause. Instead of our usual advertising selves, we’re using our powers for good and completely upgrading the National Breast Cancer Foundation‘s Pink Ribbon Breakfast site. Their goal is to have 0 deaths by 2030, which is a pretty nice goal all-round.

We built the site using Zend Framework, CSS3, and a healthy dose of jQuery-inspired Javascript.

Jump over to the site and check out our relatively-quiet first phase launch while we get ready for the donation-crazy second phase. And be sure to visit the donate link if you know someone with breasts.

Using a single controller in Zend Framework

Are you using Zend? Do you have only a core controller and don’t need extraneous URL parameters? Try this.

Most of the time, I am using Zend Framework to its (mostly) full capacity. Models, Controllers, View Helpers – the whole box-and-dice. However, there has been several occasions where I’ve only needed a single controller serving up mostly static pages, or pages leveraging an external service.

The biggest problem that arises in this case when using the default Zend Router, is that action names are treated as controller names. I don’t know about you, but I personally hate seeing http://example.com/index/my-action when what I actually want to see is http://example.com/my-action.

Here’s a nice way to completely tidy up all your actions, serving them from a single controller. (I use a Bootstrap file to initialise my application):

This basically says that my first parameter is always going to be an action name, and everything else is to be parsed as normal. I set request defaults in the array. In this case, the default controller is “index”. This allows everything to be passed straight through to my IndexController.

Addtionally, if you are using modules and want to retain routing for these also (for example, a one-controller site with an admin module), you can add this route rule to your system:

This says that anything starting with “admin” needs to be routed to the admin module, and the rest of the URL is to be parsed as normal.

That’s it! This will allow you to route all requests to a single controller for the front-end, and still maintain a complete module for the administration on the back-end.

Hopefully this cleared up some things for others, as I found the Zend Framework documentation to be quite dismal.

Using memcache and Zend_Cache

Probably one of the more useful things you can do with memcache is drop it into Zend Framework. Here’s how I did that.

Following on from the previous post, here is an example of how you can set up memcache to serve as a cache for your Zend project.

I like to use the method style of bootstrapping my application, so here’s the function that builds the cache for me.

Originally, I was getting the “Memcache::addServer function expects at most 6 parameters, 8 given” warning. To force Zend to play nice with memcache (and send the right parameter count), you need to make sure you have the compatibility option set to true in the backend options array.

Here’s an example on how to use:

Hope this helps in getting started with Zend_Cache (even on a technology as old as memcache).

Watching your Language

Inspired somewhat by Dave Ray’s post “Say Something Nice About Every Language You’ve Used“, I’ve decided to do the same.

PHP
Fairly easy to learn, and with an improving OO model, Web development will only get better. Syntax is pretty straight forward and it’s easy to get something working relatively quickly.

Visual Basic
Very simple syntax, and a good introductory language for learning Windows programming.

C/C++
I like C (and C++) because you can do with it what you will. There’s a lot of flexibility and room to move for whatever problem you have.

Java
It has a similar syntax to C, but automatic garbage collection makes me weep tears of joy.

Javascript
One of my favourite aspects of web development is putting on my Javascript hat and adding very slick functionality to my site. Simple syntax and a lot of power for overriding default objects.

Objective-C
Very quick to learn the basic syntax, and it forces a separation of code into conceptual pieces that I agree with.

That exercise is actually enlightening. I think focussing on the strengths of a particular language allows you to leverage it for maximum effectiveness. I’m fairly sure I’ve picked up more languages than this in the past, but not with enough experience for any sort of nice opinion. Perhaps next time I’ll just bitch and moan about all the languages I’ve used.

Return JSON data with Zend Framework

Getting Zend to return JSON data can be tricky at times. The JSON helper likes to send the ‘official’ JSON header (application/json), and most browsers are treating that as a download link, resulting in no data to the client and an unfortunate download box.

To bypass this default behaviour, you’ll need to tell the controller how to serve your JSON data:

The key part of this stub is the exit; line. It prevents the view renderer from sending anything, keeping your JSON data intact. Note: json_encode and json_decode only works from PHP version 5.2.1

To output all of your view’s variables in this way, replace $some_var; with:

Hopefully this saved someone a headache or two when dealing with Zend’s puzzling JSON implementation.

Modal View Controller Example – Part 2

In the first part of this tutorial, we set up a pair of simple views in Interface Builder that we switched between modally. In this tutorial, we’ll make them somewhat useful and pass data between them using delegates.

The concept of protocols and delegates is an important and somewhat complex one, but I like to think of it in these simplified terms:

Basically, the object that implements our protocol agrees to implement the methods of that protocol. In the case of this tutorial, we’ll be connecting the modal view with our main view using a delegate.

Firstly, we’ll create the interface elements for our project. Open the ModalViewExampleViewController XIB file and create a button and a label as shown.

Next, add those interface elements to ModalViewExampleViewController.h. We’re also adding the necessary IBAction also:

Be sure to include the necessary additions to ModalViewExampleViewController.m:

Jump to Interface Builder and be sure to link the new elements with the properties we defined. Refer to Part 1 of this tutorial for a guide on how to do that.

The next step is key. We will create a basic protocol and then assign a delegate. Open up ModalViewExampleViewController.h and add this:

We then tell ModalViewExampleViewController to implement this protocol:

We also need to add the protocol’s method to the main implementation:

Once we have these in place, the next step is to set up a reference between the two views. What we will do is define a delegate inside of SampleView so that we can send messages to it.
Include the protocol in ModalViewExampleViewController.h and add the reference:

Be sure to synthesize the delegate in SampleViewController.m, and include the necessary header files.

So far we have defined a protocol inside of our parent view, and defined a delegate in our modal view. The next step is to link them together and make them useful.
Firstly, we’ll write the functions that will handle the messages. Replace the original definition of didReceiveMessage with this:

And also add the following code to showWithDelegate:

What we’ve done is create a SampleView object and assigned its delegate to be the parent view. That is, the parent view will be handling messages sent by SampleView.
Open up SampleViewController.m and add the code to send the message.

Compile the app and run it. You should be able to see the text “Hello World” passed from one view to another once you dismiss your modal view with delegate. You can extend this any way you like with additional controls on the modal view, such as sliders or text input.

Download the source code for this project here.