Feshop类重写完整实例

技术分享 · ycjnx · 于 5年前 发布 · 3050 次阅读

重写Fecshop类的实例,请仔细看代码中的注释

注意:此重写类没有继承的概念,也就是说新类与原类是一个替换关系,原类中的方法如果在新类中没有编写则不能直接使用。

Fecshop中原有的类(My类这是我补充的,做个示例!)vendor目录下的修改在Fecshop升级后会消失!

[webadmin@centos7 eltmall] #11> vim /mywork/eltmall/vendor/fancyecommerce/fecshop/app/appfront/helper/My.php
<?php
namespace fecshop\app\appfront\helper;
class My
{
    /**
     * @property $price | Float ,价格
     * @property $bits | Int , 小数点后几位的格式,譬如4.00
     * @return float, 返回格式化后的数据
     * 一般用于模板中,按照显示格式显示产品数据。
     */
    public static function price($price, $bits = 2)
    {
        return number_format($price, $bits);
    }
}
[webadmin@centos7 eltmall] #11>

在视图中调用Fecshop中的My类:

[webadmin@centos7 eltmall] #11> vim /mywork/eltmall/appfront/theme/terry/theme01/mytest/customer/index.php
use fecshop\app\appfront\helper\My;
echo "<br>Helper".My::price(1.5896); 
[webadmin@centos7 eltmall] #11>

调用My类控制器的写法

[webadmin@centos7 eltmall] #11> vim /mywork/eltmall/appfront/local/local_modules/Mytest/controllers/CustomerController.php
<?php
namespace appfront\local\local_modules\Mytest\controllers;
use fecshop\app\appfront\modules\AppfrontController;
use Yii; 
use yii\web\Response;
class CustomerController extends AppfrontController
{
......
......
    public function actionIndex(){
        //echo "ID:".$this->action->id;exit;
        return $this->render($this->action->id);
    }    
}
[webadmin@centos7 eltmall] #11> 

重写My类之前调用的结果,输出了两位小数,正确:

http://www.emall.com/mytest/customer/
Helper1.59

在本地编写My类:

[webadmin@centos7 eltmall] #11> vim /mywork/eltmall/appfront/helper/My.php
<?php
namespace fecshop\app\appfront\helper;
//namespace appfront\helper;//此句是错误的写法!
class My{
    //修改了一下,默认取3位小数
    public static function price($price, $bits = 3){
        return number_format($price, $bits);
    }
}
[webadmin@centos7 eltmall] #11>

使用类映射实现类重写:

[webadmin@centos7 eltmall] #11> vim /mywork/eltmall/appfront/config/YiiClassMap.php
<?php
return [
    //'fecshop\app\appfront\helper\My',Feschop系统中的原类
	//'@appfront/helper/My.php',本地的新类
    'fecshop\app\appfront\helper\My' => '@appfront/helper/My.php',
    //'fecshop\services\Service'  => '@fecshop/enterprise/services/Service.php',
];
[webadmin@centos7 eltmall] #11>

重写My类之后调用的结果,结果是三位小数:OK

http://www.emall.com/mytest/customer/
Helper1.590

(全文完)

共收到 1 条回复
Aswe#15年前 1 个赞

赞!简明清晰:+1:

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics