和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
结束。愉快编程~