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';
  } 
}
2
  • Removed Var/Generation and Var/Cache folder from your magento2 root directory and Run php bin/magento setup:di:compile command Jan 17, 2017 at 9:48
  • Just remove var folder from root. 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

4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.