我有一個名稱空間爲Demo\HelloWorld\Model\Customer
的模型,模型中有一個函數demo()print「Hello World!」。如何從Magento2中的控制器調用模型方法
如何從名爲空間的控制器調用函數demo()Demo\HelloWorld\Controller\Index
?
在此先感謝!
我有一個名稱空間爲Demo\HelloWorld\Model\Customer
的模型,模型中有一個函數demo()print「Hello World!」。如何從Magento2中的控制器調用模型方法
如何從名爲空間的控制器調用函數demo()Demo\HelloWorld\Controller\Index
?
在此先感謝!
只需在控制器的構造函數中注入模型,Objectmanager將爲您完成所有工作。這應該是這樣的:
<?php
namespace Demo\HelloWorld\Controller;
class Index extends \Magento\Framework\App\Action\Action
{
protected $customerModel;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Demo\HelloWorld\Model\Customer $customerModel
) {
$this->customerModel = $customerModel;
parent::__construct($context);
}
public function execute()
{
$this->customerModel->demo();
}
}
如果你的模型\Demo\HelloWorld\Model\Customer
背後都有一個表,你應該使用一個工廠來實例化。
工廠不需要創建,它將自動生成的,但你需要在控制器的構造函數注入它:
<?php
namespace Demo\HelloWorld\Controller;
class Index extends \Magento\Framework\App\Action\Action
{
protected $customerFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Demo\HelloWorld\Model\CustomerFactory $customerFactory
) {
$this->customerFactory = $customerFactory;
parent::__construct($context);
}
public function execute()
{
$customer = $this->customerFactory->create();
//here you can call load or any other method
//$customer->load(2);
//then call your method
$customer->demo();
}
}