我有一个带有命名空间的模型Demo\HelloWorld\Model\Customer
,模型有一个函数 demo() 打印“Hello World!”。
如何从具有命名空间的控制器调用函数 demo() Demo\HelloWorld\Controller\Index
?
提前致谢 !
我有一个带有命名空间的模型Demo\HelloWorld\Model\Customer
,模型有一个函数 demo() 打印“Hello World!”。
如何从具有命名空间的控制器调用函数 demo() Demo\HelloWorld\Controller\Index
?
提前致谢 !
如果你的模型\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();
}
}
只需将您的模型注入控制器的构造函数中,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();
}
}