Zend Framework2 - 在Controller使用自定义插件plugins 和 视图助手Helper

1、定义插件

class MyPlugin extends AbstractPlugin {

    private $myPlugin;

    public function __construct(PluginManager $pm) {
        $this->myPlugin= $pm->getServiceLocator()->get('Translator');   //插件ID     
    }
  
//使用参数
    public function __invoke($message, $textDomain = 'default', $locale = null) {
        return $this->translator->translate($message, $textDomain, $locale);
    }

}

 --- 注册插件 ----

module.config.php

'controller_plugins' = > array (
     'invokables' = > array (
         'abcPlugin'   = > Admin\Plugins\MyPlugin ,
     )
) ,


3、可以在插件中使用控制器方法

  //查询数据库

private  function getInfoTable ( )
{
     $ sm = $ this -> getController ( ) -> getServiceLocator ( ) ;
     return $ sm -> get ( 'Admin\Model\InfoTable' ) ;
}


4、在Controller调用

$this->abcPlugin('example message');


5、在控制器使用Helper

$helper = $this->getServiceLocator()->get('viewhelpermanager')->get('helperName');

$helper(params1,...);



=============在视图插件中添加方法==============

1.插件类

class InfoHelper extends AbstractHelper
{
    protected $infoTable;
    
    /**
     * 在.config中注册,注意对应的名称空间,视图中可直接调用$this->xxxx
     * $infoWhere可定义$cate_path_id: string; $categoryIds: int/array $categoryIds:指定分类ID
     * 适用于视图中调用
     * return bool
     */
    public function __invoke($infoWhere=[], $limit=null, $order=null)
    {
        $infoTable = $this->getInfoTable();        
        $where = array(
            'status'=>1,            
        );
        $where = array_merge($where, $infoWhere);
        //param: ($where=null, $qs=null, $paginated=false, $limit=null, $order=null)
        $resultSet = $infoTable->fetchAll($where, null, false, $limit, $order);        
        return $resultSet;
    }
    
    
    public function infoPhoto($infoWhere=[], $uploadWhere=[], $limit=null, $order=null)
    {        
        $infoTable = $this->getInfoTable();        
        $where = array(
            'status'=>1,
        );
        $infoWhere = array_merge($where, $infoWhere);
        
        //param: ($infoWhere=null, $uploadWhere=null, $limits=null, $order=null)        
        $resultSet = $infoTable->getInfoPhotoRowsFull($infoWhere, $uploadWhere, $limit, $order);        
        return $resultSet;
    }
    
    
    public function getInfoTable()
    {
        if (!$this->infoTable){
            $this->infoTable = $this->getView()->getHelperPluginManager()->getServiceLocator()->get('Admin\Model\InfoTable');
        }
        return $this->infoTable;
    }
    
}

2、注册插件(.config中)

3、在视图中调用helper方法

$infoPhoto = $this->plugin('infoHelper')->infoPhoto();








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值