Magento 2:使用插件&重写/重写块,模型,控制器,助手;偏爱

时间:2016-09-10 08:43:29

标签: magento2

Magento 2:使用插件覆盖/重写块,模型,控制器,助手;偏好。

如何覆盖帮助器,块,模型视图?

1 个答案:

答案 0 :(得分:5)

有两个步骤可以覆盖块,模型和控制器文件

1)在di.xml中添加覆盖首选项

2)在模块中创建块,模型和控制器文件

  

命名空间:王子

     

模块名称:Helloworld

用于覆盖目录产品ListProduct块。

1)在Folder Prince / 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\Model\Product" type="Prince\Helloworld\Model\Rewrite\Catalog\Product" />
</config>

2)在Prince Prince / Helloworld / Block / Rewrite / Product中创建ListProduct.php块文件

<?php
    namespace Prince\Helloworld\Block\Rewrite\Product;

    class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
    {
        public function _getProductCollection()
        {
            // Do your code here
        }
    }

用于覆盖目录产品型号。

1)在

之前在di.xml中添加首选项
<preference for="Magento\Catalog\Model\Product" type="Prince\Helloworld\Model\Rewrite\Catalog\Product" /> 

2)在Prince Prince / Helloworld / Model / Rewrite / Catalog

中创建Product.php模型文件
<?php
namespace Prince\Helloworld\Model\Rewrite\Catalog;

class Product extends \Magento\Catalog\Model\Product
{
    public function isSalable()
    {
        // Do your code here

        return parent::isSalable();
    }

}

用于覆盖控制器

1)在

之前在di.xml中添加首选项
<preference for="Magento\Catalog\Controller\Product\View" type="Prince\Helloworld\Controller\Rewrite\Product\View" />

2)在Prince Prince / Helloworld / Controller / Rewrite / Product

文件夹中创建View.php控制器文件

class View extends \Magento\Catalog\Controller\Product\View
{
    /**
     * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        // Do your stuff here
        return parent::execute();
    }
}

您可以使用相同的方法覆盖其他块,模型和控制器。