如何将自定义函数添加到smarty扩展yii2

时间:2019-06-05 10:16:31

标签: php yii2 smarty

我对yii2的smarty扩展有点问题。

我创建了一个新的smarty函数,并将代码添加到了此文件中:

  

backend / vendor / yiisoft / yii2-smarty / src / Extension.php

 public function __construct($viewRenderer, $smarty)
    {
        //other code
        /* CUSTOM FUNCTION REGISTER */
        $smarty->registerPlugin('function', 'test', [$this, 'functionTest']);
    }
//this is the custom function
public function functionTest($params, $template){
        return "Test custom funcion";
    }

我可以将此自定义函数用于{test}这样的模板中,并且一切正常。

今天,我已经将yii2更新为2.0.20版本,并且显然Extension.php文件已被替换,因此我无法再访问该自定义函数。 我的问题是:如何在yii2中为smarty添加自定义功能?

我将以这种方式设置配置数组:

//this is in backend/config/main.php
'view' => [

            'renderers' => [
                'tpl' => [
                    'class' => 'yii\smarty\ViewRenderer',
                    'pluginDirs' => ['@backend/saSmartyPlugin'],
                    'widgets' =>[
                                  'functions' => [['test' => 'test'], ],
                                ],
                    //'cachePath' => '@runtime/Smarty/cache',
                ],
            ],
        ],

并将其插入saSmartyPlugin文件夹中,如下所示插入我的test.php文件:

<?php
    class Test{
        function functionTest($params, $template){
           return "Test custom funcion";
        }
    }

但是我得到这个错误:

  

聪明:注册模板类中未定义的类“测试”

enter image description here

2 个答案:

答案 0 :(得分:0)

我同意Muhammad Omer Aslam的观点,您应该从backend / vendor / yiisoft / yii2-smarty / src / Extension.php扩展,以便创建任何新方法并在更新后可以使用它们。之后,您只需将配置文件路径写入扩展类即可。

答案 1 :(得分:0)

我会找到一个有关@MuhammadOmerAslam和@SergheiLeonenco的建议的解决方案。 我为有这个问题的任何人写这个答案。

首先,我创建我的PHP文件Test.php,并扩展了Smarty的Extension类

namespace common\components;

use yii\smarty\Extension;

class Test extends Extension{

    public function __construct($viewRenderer, $smarty){ 

        parent::__construct($viewRenderer, $smarty);// call parent construct
        $smarty->registerPlugin('function', 'bread', [$this, 'functionBreadcrumbs']);//register my custom function
    }
    //My custom function
    function functionTest($params, $template){
       return "Test custom funcion";
    }

然后我将此文件保存到common/components/

之后,我修改了config.php文件

'view' => [

            'renderers' => [
                'tpl' => [
                    'class' => 'yii\smarty\ViewRenderer',
                    'extensionClass' => 'common\components\Test'
                ],
            ],
        ],

    ],