I have a controller and I want to call specific function of model from controller file, When I try to call function, I got an error like this :
Fatal error: Uncaught TypeError: Argument 2 passed to Lime\Hello\Controller\Index\Index::__construct() must be an instance of Lime\Hello\Model\Sync, instance of Magento\Framework\View\Result\PageFactory given, called in
here's my controller file code:
namespace Lime\Hello\Controller\Index;
use Magento\Framework\App\Action\Context;
class Index extends \Magento\Framework\App\Action\Action
{
protected $_sync;
public function __construct(\Magento\Framework\App\Action\Context $context, \Lime\Hello\Model\Sync $sync)
{
$this->_sync = $sync;
parent::__construct($context);
}
public function execute()
{
$run = $this->_sync;
echo $run->test();
exit;
}
}
here's my model file code:
namespace Lime\Hello\Model;
use Magento\Framework\Object;
class Sync extends Object
{
public function test(){
return 'a';
}
}
1 Answer 1
Change construct of your model as below
public function __construct(\Magento\Framework\App\Action\Context $context, \Lime\Hello\Model\SyncFactory $sync)
{
$this->_sync = $sync;
parent::__construct($context);
}
Change below execute method code
public function execute()
{
$run = $this->_sync->create();
echo $run->test();
exit;
}
I have added create() in above code
-
SyncFactory i have called model there you need to use create for model instance as i have done in execute methodPrashant Valanda– Prashant Valanda2017年01月17日 10:08:04 +00:00Commented Jan 17, 2017 at 10:08
-
solution is working but could you please explore it more why we need write SyncFactory place of simple Sync.akgola– akgola2017年12月14日 07:02:09 +00:00Commented Dec 14, 2017 at 7:02
-
refer this link devdocs.magento.com/guides/v2.0/extension-dev-guide/…Prashant Valanda– Prashant Valanda2017年12月14日 08:39:45 +00:00Commented Dec 14, 2017 at 8:39
Var/GenerationandVar/Cachefolder from your magento2 root directory and Runphp bin/magento setup:di:compilecommand