1

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';
 } 
}
Dhiren Vasoya
9,70914 gold badges37 silver badges61 bronze badges
asked Jan 17, 2017 at 9:42
2
  • Removed Var/Generation and Var/Cache folder from your magento2 root directory and Run php bin/magento setup:di:compile command Commented Jan 17, 2017 at 9:48
  • Just remove var folder from root. Commented Jan 17, 2017 at 9:52

1 Answer 1

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

answered Jan 17, 2017 at 9:57
3
  • SyncFactory i have called model there you need to use create for model instance as i have done in execute method Commented 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. Commented Dec 14, 2017 at 7:02
  • refer this link devdocs.magento.com/guides/v2.0/extension-dev-guide/… Commented Dec 14, 2017 at 8:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.