在 magento 2 中修改函数的一些方法

重写类

档案: Namespace/ModuleName/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">
   <preference for="Magento\Catalog\Controller\Product\View" type="Namespace\ModuleName\Controller\Product\View" />
</config>

档案: Namespace\ModuleName\Controller\Product\View.php

class View extends \Magento\Catalog\Block\Product\View
{
    ///Code logic here
}

插入对象

档案: Namespace/ModuleName/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">
        <type name="Magento\Catalog\Model\Product">
            <plugin name="name_of_plugin" type="Namespace\ModuleName\Plugin\Catalog\Model\Product" sortOrder="1" disabled="false" />
        </type>
    </config>

档案: Namespace\ModuleName\Plugin\Catalog\Model\Product.php

namespace Namespace\ModuleName\Plugin\Catalog\Model;
 
class Product
{
    public function beforeSetName(
        \Magento\Catalog\Model\Product $product, string $name)
    {
        /// Code logic here   
        return $name;
    }
 
    public function afterGetName(
        \Magento\Catalog\Model\Product $product, string $name)
    {
         /// Code logic here    
        return $name;
    }
 
    public function aroundSave(
        \Magento\Catalog\Model\Product $product, \Closure $proceed)
    {
        $this->doSomethingBeforeSave();
        $result = $proceed();
        if ($result) {
            $this->doSomethingAfterSave();
        }
        return $result;
    }
}