Zend Framework 2 入门-使用插件扩展你控制器

来源:互联网 发布:pic单片机液晶屏显示 编辑:程序博客网 时间:2024/05/18 00:48

有时候控制器中的代码过多会对我们的操作造成不便。那么有什么好的办法呢?下面将为大家介绍一个控制器的插件。

首先,我们新建一个插件感受下他的作用

<?php/** * 插件示例 * * @author Star <wmistar@gmail.com> * @license http://mushroot.com * @version: 1.0 * */namespace Application\Controller\Plugin;use Zend\Mvc\Controller\Plugin\AbstractPlugin;class ExamplePlugin extends AbstractPlugin{      public function sayHello()      {          echo 'Hello';      }}

那么接下来怎么去使用这个插件呢
我们需要在module.config.php中添加这个插件的信息
(path: /Module/Application/module/config.php)

//添加'controller_plugins' => array(    'invokables' => array(        'ExamplePlugin'   => 'Application\Controller\Plugin\ExamplePlugin',    )),

这个时候就可以直接在控制器中使用当前插件了

 <?php/** * 首页控制器文件 * * @author Star <wmistar@gmail.com> * @license http://mushroot.com * @version: 1.0 * */namespace Application\Controller;use Zend\Mvc\Controller\AbstractActionController;use Zend\View\Model\ViewModel;class IndexController extends AbstractActionController{    public function indexAction()    {        $examplePlugin = $this->ExamplePlugin();        $examplePlugin->sayHello(); //打印出‘Hello’    } }

那么他既然是控制器插件,是否能直接调用控制器的一些方法呢?
查看AbstractPlugin会发现其拥有getController()和setController()方法;
那么我们怎么来使用呢,比如我们在插件中操作数据库就可以这样来操作:

public function getUser($id) {    return $this->getUserTable()->getUser();}private function getUserTable(){    $sm = $this->getController()->getServiceLocator();    return $sm->get('Table\User\UserTable');}
转自http://mushroot.com/zf2-zend-framework-2-rumen-shiyongchajiankuozhannidekongzhiqi


0 0