magento 2.x中magento 1.x模型的等价物是什么

Abh*_*deo 5 php zend-framework magento magento2

我是magento2的新手,我发现很难在新版本中获得常规代码片段.所以,请帮助我在这里解释magento2中以下片段的等价物:

Mage::getModel('catalog/product')->getCollection();
Mage::getModel('sales/order');
Mage::getModel('catalog/category')->getCollection();
Mage::getModel('customer/customer');
Mage::getModel('cart/quote');
Mage::getModel('checkout/cart');
Mage::getSingleton('customer/session');
Mage::getModel('catalog/category')->load(id);
Run Code Online (Sandbox Code Playgroud)

我希望这个问题能帮助所有新的magento 2开发人员在一个地方找到相关的查询.

Mar*_*ius 2

在 magento 2 中,不再有用于实例化模型的静态方法。
您必须使用依赖注入。
对于不可注入的模型,您可以使用工厂来实例化模型。
不可注射的是例如产品模型、订单模型……通常您可以调用加载。这包括收藏。
可注入的东西,你可以直接注入到你的构造函数中。
例如,客户会话是可注入的。

假设您必须在您的一门课程中使用上述模型。
我将把它们全部添加到一个类中,但你可以只使用你需要的。

class MyClass extends SomeOtherClass
{
    protected $productCollectionFactory;
    protected $orderFactory;
    protected $categoryCollectionFactory;
    protected $customerFactory;
    protected $cart;
    protected $customerSession;
    protected $categorFactory;
    public function __construct(
       ... //you can have some other parameters here
       \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
       ... //you can have other parameters here
    ) {
        ....
        $this->productCollectionFactory = $productCollectionFactory;
        $this->orderFactory = $orderFactory;
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        $this->customerFactory = $customerFactory;
        $this->cart = $cart;
        $this->customerSession = $customerSession;
        $this->categoryFactory = $categorFactory;
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以像这样在你的课堂上使用它们。

要获取产品集合,您可以执行以下操作:

$productCollection = $this->productCollectionFactory->create();
Run Code Online (Sandbox Code Playgroud)

要获取订单模型的实例,请执行以下操作:

$order = $this->orderFactory->create();
Run Code Online (Sandbox Code Playgroud)

类别集合

$categoryCollection = $this->categoryCollectionFactory->create();
Run Code Online (Sandbox Code Playgroud)

客户实例

$customer = $this->customerFactory->create();
Run Code Online (Sandbox Code Playgroud)

magento 2 中不存在购物车/报价。

对于结帐车,您可以简单地使用,$this->cart因为它是可注射的。
客户会话也是如此。这些是单身人士。

获取类别

 $category = $this->categoryFactory->create()->load($id);
Run Code Online (Sandbox Code Playgroud)