link-in - רשומות קוד

חפש את הקוד שלך >

דריסה של מודול : Overview of block, model, controller, helper

ביצוע של דריסה או הרחבה של פונקציות קיימות:

  1. בניה של המודול או מציאת המודול הקיים
  2. העתקת הקלאסס הרצוי 
  3.  di.xml רישום הדריסה

Using Plugin VS Using Preference

plugin : תוספת של מגנטו 2 , מאפשר דריסה או התערכבות בנקודות זמן ( לפי , אחרי וכו') , הדרך היותר נכונה 

Preference : דריסה מלאה של הקלאס 

Plugin

MODEL OVERRIDE

app/code/Mageplaza/HelloWorld/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="Mageplaza-yourmodule-product-model" type="Mageplaza\HelloWorld\Plugin\ProductPlugin" sortOrder="1" />
    </type>    
</config>

app/code/Mageplaza/HelloWorld/Plugin/ProductPlugin.php

<?php
 
namespace Mageplaza\HelloWorld\Plugin;
 
class ProductPlugin
{    
    public function beforeSetName(\Magento\Catalog\Model\Product $subject, $name)
    {
        // logging to test override    
        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface');
        $logger->debug('Model Override Test before');
        
        return $name;
    }
            
    public function afterGetName(\Magento\Catalog\Model\Product $subject, $result)
    {            
        // logging to test override    
        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface');
        $logger->debug('Model Override Test after');
        
        return $result;
    }    
}
?>

Preference

BLOCK OVERRIDE

app/code/Mageplaza/HelloWorld/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\Block\Product\View" type="Mageplaza\HelloWorld\Block\Catalog\Product\View" />
</config>

app/code/Mageplaza/HelloWorld/Block/Catalog/Product/View.php

<?php
 
namespace Mageplaza\HelloWorld\Block\Catalog\Product;
 
class View extends \Magento\Catalog\Block\Product\View
{
    /**
     * Retrieve current product model
     *
     * @return \Magento\Catalog\Model\Product
     */
    public function getProduct()
    {
        // logging to test override    
        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface');
        $logger->debug('Block Override Test');
        
        if (!$this->_coreRegistry->registry('product') && $this->getProductId()) {
            $product = $this->productRepository->getById($this->getProductId());
            $this->_coreRegistry->register('product', $product);
        }
        return $this->_coreRegistry->registry('product');
    }
}
?>

חשוב לשים לב !! לעשות extends ולהוסיף / בתחילת הנתיב