Creating and loading a controller plugin is easy in ZF2, be aware that the loading method has changed on beta 5, and hopefully it will stay stable from now on.

On my previous post I described how to get started with zf2 using a skeleton application, so I will start from there.

I will create a new folder named «Plugin» under «module/Empirio/src/Empirio/Controller» and then create a new file named «MyFirstPlugin.php», which will be a php class that will extend the «AbstractPlugin»:

module/Empirio/src/Empirio/Controller/Plugin/MyFirstPlugin.php
<?php
namespace Empirio\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class MyFirstPlugin extends AbstractPlugin{
    public function doSomething(){
        // ...
    }
}

Now after we have created the plugin, we need to load it on our application, we do this on our module config file, by adding those lines of code:

module/Empirio/config/module.config.php
<?php
return array(
    // ... your configuration

    'controller_plugins' => array(
        'invokables' => array(
            'MyFirstPlugin' => 'Empirio\Controller\Plugin\MyFirstPlugin',
        )
    ),

    // ...
);

Now we can call the plugin inside the controller by just doing this:

module/Empirio/src/Empirio/Controller/IndexController.php
<?php
namespace Empirio\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController{
    public function indexAction(){
        $plugin = $this->MyFirstPlugin();
        $plugin->doSomething();

        return new ViewModel();
    }
}

And that’s it. Comments are welcome on twitter.