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

What are the equivalents of magento 1.x models in magento 2.x

我是 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);

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

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

假设您必须在 classes 之一中使用上述模型。
我会将它们全部添加到一个 class 中,但您可以只使用您需要的。

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;
        ....
    }
}

然后你可以像这样在你的 class 中使用它们。

要获得产品 collection,您可以这样做:

$productCollection = $this->productCollectionFactory->create();

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

$order = $this->orderFactory->create();

类别collection

$categoryCollection = $this->categoryCollectionFactory->create();

客户实例

$customer = $this->customerFactory->create();

cart/quote 在 magento 2 中不存在。

对于结账车,您可以简单地使用 $this->cart,因为这是可注射的。
客户 session 也一样。这些是单身人士。

获取类别

 $category = $this->categoryFactory->create()->load($id);