magento2中的对象管理器助手以及代码示例
  • Magento
  • 2023-03-01 22:33:31
  • 29661 阅读

在Magento 2中,对象管理器(Object Manager)是一个用于创建和管理类实例的核心组件。您可以通过依赖注入或使用对象管理器助手(Object Manager Helper)获取对象管理器的实例。


以下是一个简单的示例:


use Magento\Framework\App\ObjectManager;
use Magento\Catalog\Api\ProductRepositoryInterface;
class MyCustomClass
{
    private $productRepository;
    public function __construct()
    {
        $objectManager = ObjectManager::getInstance();
        $this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
    }
    public function getProductById($id)
    {
        return $this->productRepository->getById($id);
    }
}

在上面的示例中,我们创建了一个名为 MyCustomClass 的类,并使用对象管理器助手获取了 ProductRepositoryInterface 的实例。我们还在构造函数中初始化了 $productRepository 属性,并使用该属性来获取指定 $id 的产品。


请注意,使用对象管理器助手在Magento 2中是不推荐的。它应该只用于临时解决方案和快速的原型开发。推荐使用依赖注入来获取所需的类实例。