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):

'controller_plugins' => [
    'factories' => [
        Controller\Plugin\DataModifierPlugin::class => InvokableFactory::class,
    ],
    'aliases' => [
        'DataModifierPlugin' => Controller\Plugin\DataModifierPlugin::class,
    ]
],

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

module/Application/src/Application/Controller/Plugin/DataModifierPlugin.php

And example content:

namespace Application\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
 
class DataModifierPlugin extends AbstractPlugin
{

    public function modifyString(string $test) : string
    {
        return $test . ' MODIFIED!';
    }

    // Other functions
}

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

<?php

namespace Application\Controller;

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

class IndexController extends AbstractActionController
{
    public function pleaseModifyAction()
    {
        // Get some data from model

        $newData = $this->DataModifier->modifyString($old);
        $newData2 = $this->DataModifier->modifySomething($old2);

        // Maybe something else with ref?
        $this->DataModifier->fooBar($old3);

        return new ViewModel(array(
            'data' => $newData,
            'data2' => $newData2,
        ));
    }
}

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.