使用
ObjectManager
,但Magento 2不建议使用此解决方案。
<?php
include('app/bootstrap.php');
use Magento\Framework\App\Bootstrap;
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$productId = 1;
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
echo $product->getName();
?>
推荐的解决方案(Magento 2)
在magento 2中,建议使用
ProductRepository
和
ProductFactory
在一个合适的自定义模块而不是简单的php文件中。好吧,通过使用下面(推荐)的代码,您可以在自定义块中加载产品。
产品工厂
解决方案
<?php
namespace [Vendor_Name]\[Module_Name]\Block;
use Magento\Catalog\Model\ProductFactory;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_productloader;
public function __construct(
ProductFactory $_productloader
) {
$this->_productloader = $_productloader;
}
public function getLoadProduct($id)
{
return $this->_productloader->create()->load($id);
}
}
在Magento 2.1中
产品存储库
解决方案
namespace [Vendor_Name]\[Module_Name]\Block;
use Magento\Catalog\Api\ProductRepositoryInterface;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_productRepository;
public function __construct(
ProductRepositoryInterface $productRepository
) {
$this->_productRepository = $productRepository;
}
public function getProduct($id)
{
return $product = $this->productRepository->getById($id);
}
}
还有,你的
.phtml
文件应如下所示:
$productId = 1;
$product = $this->getLoadProduct($productId);
echo $product->getName();
我希望,你已经知道如何在magento 2中创建一个自定义模块,或者如果你想的话,那就看看这篇博文
How to create a basic module in Magento 2