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()
.
After deploying the module on a new CentOS dev environment, remove the var/di and var/generation folders and recompile di, it works. Before that I used an Win Xampp environment. That causes a lot of trouble...
Best Answer
You could use regular JSON response class: