gpt4 book ai didi

php - magento 2.x 中 magento 1.x 模型的等效项是什么

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:43:41 26 4
gpt4 key购买 nike

我是 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 中,不再有用于实例化模型的静态方法。
你必须使用依赖注入(inject)。
对于不可注入(inject)的模型,您可以使用将实例化模型的工厂。
不是注入(inject)剂,例如产品模型、订单模型……通常是您可以调用加载项的东西。这包括集合。
可注入(inject)的,你可以在你的构造函数中注入(inject)。
例如,客户 session 是可注入(inject)的。

假设您必须在其中一个类(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;
....
}
}

然后你就可以像这样在你的类里面使用它们了。

要获取产品集合,您可以这样做:

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

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

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

分类收藏

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

客户实例

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

magento 2 中不存在 cart/quote。

对于结帐购物车,您可以简单地使用 $this->cart,因为它是可注入(inject)的。
客户 session 相同。这些是单例。

获取类别

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

关于php - magento 2.x 中 magento 1.x 模型的等效项是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39635619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com