Skip to content

How to create your own controller plugin in ZF2?

Last updated on December 21, 2022

Our step-by-step guide explains how you can create your own controller plugin in zf2. Fortunately creating a controller plugin is a very easy task.

Create a directory called plugin in your module controller directory, then create a file Myfunction.php

Myfunction.php file is a PHP class that will extend the zf2’s AbstractPlugin, getCurrentuserID() is our sample method, you can create an ‘n’ number of methods with an ‘n’ number of arguments.

namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class MyFunctions extends AbstractPlugin {

    public function getCurrentuserID(){
        // ...
    }

}

After creating the plugin we need to register the plugin into your module config, open your plugin module’s module.config.php file, then put in the blow code.

return array(
    // ... your configuration
    'controller_plugins' => array(
        'invokables' => array(
            'Myfunction' => 'Application\Controller\Plugin\Myfunction',
        )
    ),

    // ...
);

Now we can call the plugin inside any controller by just calling this $plugin = $this->Myfunction();.

namespace Application\Controller;

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

class IndexController extends AbstractActionController {
    public function indexAction() {
        $plugin = $this->Myfunction();
        $plugin->getCurrentuserID();
        return new ViewModel();
    }
}

Here is an example.

That’s it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments