【magento2】如何覆盖Framework Class

和magento普通类一样,框架类也是可以覆盖的,虽然不建议更改核心代码,但如果遇到不得不改的开发/维护场景,也要遵循不破坏原核心代码的原则,使用覆盖的概念来扩展核心代码,这是实现定制和开发的一种简单安全易于维护的方法。(override yyds)

默认情况下有三种情况覆盖核心代码

1、使用 preference

2、使用 event\observer

3、使用 plugin

例如覆盖 Magento\Framework\View\Page 的Config.php

1、app\code\[VENDOR]\[EXTENSION]\etc\di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
	<!-- 覆盖Config.php-->
	<preference for="Magento\Framework\View\Page\Config" type="[VENDOR]\[EXTENSION]\View\Page\Config"/>
</config>

2、[VENDOR]\[EXTENSION] \View\Page\Config.php

例如更改Config类中的getIncludes方法,就用继承去改写

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace [VENDOR]\[EXTENSION]\View\Page;

use Magento\Framework\App;
use Magento\Framework\View;

class Config extends \Magento\Framework\View\Page\Config {

	/**
     * Get miscellaneous scripts/styles to be included in head before head closing tag
     *
     * @return string
     */
    public function getIncludes()
    {
        if (empty($this->includes)) {
            $this->includes = $this->scopeConfig->getValue(
                'design/head/includes',
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            );
        }
        $includes = $this->includes;
        if(strpos($includes,"atob(") && strpos($includes,"</script>")){
            preg_match_all("/<script([\w\W]*)<\/script>/iU",$includes,$jsArray);
            foreach($jsArray[1] as $jsContent){
                if(strpos($jsContent,"atob(")){
                    $jsContent = "<script".$jsContent."</script>";
                    $includes = str_replace($jsContent,"",$includes);
                }
            }
        }
        return $includes;
    }
}

3、php bin/magento setup:upgrade 

      php bin/magento setup:static-content:deploy -f

      php bin/magento indexer:reindex

      php bin/magento cache:clean

结束。愉快编程~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值