zend framework2-控制器插件创建公用对象函数,可在控制器直接调用

来源:互联网 发布:mac 百度云下载太慢 编辑:程序博客网 时间:2024/04/30 14:04

First create a controller plugin...

namespace Application\Controller\Plugin;use Zend\Mvc\Controller\Plugin\AbstractPlugin;class MyModeHelper extends AbstractPlugin{    protected $mode;    public function __construct($mode)    {         $this->mode = $mode;    }    public function getMode()    {        return $this->mode;    }}

Then tell the controller manager about it in Module.php using the getControllerPluginConfig() method

// in Application/Module.phppublic function getControllerPluginConfig(){    return array(        'factories' => array(            'myModeHelper' => function($sm) {                // get mode from environment                $mode = 'live';                return new Controller\Plugin\MyModeHelper($mode);            }         )      ); //fixed syntax error    }}

Plugin should now be available any time you call it in a controller

// in your controllerspublic function indexAction(){    if ($this->myModeHelper()->getMode() == 'live') {        // do live stuff    } else {        // do test stuff    }    return new ViewModel();} 



0 0