Zend Framework – create custom controller plugin

Few weekes ago I wrote about custom view plugins in Zend Framework. It’s great solution to separate and re-use code for our templates, build simple functions for menus, thumbnails etc. But… what about similar situation in controller? Yes, it’s possible to use view helpers in controllers, but it isn’t good. Creating controller plugin is much better option and we can do that in Zend Framework. Let’s try.

Why and when should we use controller plugins? Thanks to them we can separate some code, that can be used in many places in our app. And we shouldn’t always create new base class for controllers and extend AbstractActionController – we should use plugins. Maybe special class for merging files? Maybe format converter? There are plenty of uses and it depends on our application. Let’s say we want modify some data from model before we send it to view. First step is to declarare our plugin in module config (in default, module.config.php):

Now we can create plugin class. Path must complies with our config decalaration, so we add new file:

And example content:

And… it’s all. Now we can use our new plugin in controller. How? It’s also very simple:

As you can see, we can create many methods, plugin can also own properties etc. There are also some build-in Zend controller plugins. You should know them: Url, Params or Layout are only examples. With custom plugins, you can easily extend controllers functionality.