Call Model Method from Controller in Magento 2

controllersmagento2model

I have a model with namespace Demo\HelloWorld\Model\Customer and model have a function demo() print "Hello World !".

How to call function demo() from Controller with namespace Demo\HelloWorld\Controller\Index ?

I try example here but not working.

Recoverable Error : Argument 1 passed to
Demo\HelloWorld\Controller\Index\Index::__construct() must be an
instance of \Magento\Framework\ObjectManager, instance of
Magento\Framework\App\Action\Context given

Best Answer

The object manager is not the correct way to do this. Use dependency injection via the constructor whenever possible.

You are getting that error because your controller extends another class, but you are not following the parent class's constructor, or you did not clear the cache.

You have not provided your code, but I assume your controller extends \Magento\Framework\App\Action\Action. If you open that, you'll see the constructor signature for that class is:

/**
 * @param \Magento\Framework\App\Action\Context $context
 */
public function __construct(
    \Magento\Framework\App\Action\Context $context
) {
    // ...
}

You're getting the error because Magento is trying to inject a Context object, and you're asking for a Customer. To inject your model, your class constructor needs to look like this:

protected $customer;

/**
 * @param \Magento\Framework\App\Action\Context $context
 * @param \Demo\HelloWorld\Model\Customer $customer
 */
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Demo\HelloWorld\Model\Customer $customer
) {
    $this->customer = $customer;

    parent::__construct($context);
}

Make that change, then flush the Magento cache (or folder var/cache), and then it should work.

Note: This is assuming your Customer class is injectable. If it's loaded from the database, you need to inject CustomerFactory instead, and then call $customer = $this->customerFactory->create().

Related Topic