简体   繁体   中英

ZF2 MVC global function

What is best practice for making a function/method global to the application for several controllers?

For example lets say we have a controller. This controller is using a function, but instead of copy pasting it to another controller, we just want to make a call to that function.

class ControllerName extends AbstractActionController {
    // Your actions

    // Has to become a call,
    // instead of copy pasting this function to several controllers
    public function GlobalFunction ($parameter) {
        //Use parameter and return something
    }
}

Creating ControllerPlugins is one solution, I've also read about creating and setting up a StdLib . So what is the best practice for a function which will only be called at the controllers?

Two other related questions:

The plugin that is described in the accepted answer will do the job. But in what case you do NOT want to use a plugin and will go for another solution? I just want to brighten it up, since I did not find enough documentation about it.

Another point of interrest. What if this plugin has to be available to several modules aswell? Setting up the plugin within the application and setting it up in the module\\Application\\Config\\module.config.php or within the Config\\Autoload\\Global.php of theZend App?

You probably want to look at the several Zend\\Mvc\\Controller\\Plugin -Classes provided. Ultimately it all depends on what your "global function" is supposed to do. It may either be suited to do it as a ControllerPlugin or it may better be suited as a functionality provided by one of your Services.

To write your own ControllerPlugin, do it like the following:

namespace Yournamespace\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

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

Register your plugin at configuration, either inside getConfig() with the top-level-array-key or inside your Modules getControllerPluginConfig() without the top-level:

'controller_plugins' => array(
    'invokables' => array(
        'yourPlugin' => 'Yournamespace\Controller\Plugin\YourPlugin',
    )
),

And simply use it:

public function indexAction()
{
    $plugin = $this->yourPlugin();
    $plugin->doSomething();

    return new ViewModel();
}

If you just want to call $this->yourPlugin($paramX, $paramY) , then you have to define a __invoke() method to your ControllerPlugin.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM