LinoPham
LinoPham

Reputation: 101

How to call a model method from controller in Magento2

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 ?

Thanks in advance !

Upvotes: 0

Views: 5715

Answers (2)

Marius
Marius

Reputation: 15216

if your model \Demo\HelloWorld\Model\Customer has a table behind it you should use a factory to instantiate it.
The factory does not need to be created, it will be autogenerated, but you need to inject it in the constructor of your controller:

<?php
namespace Demo\HelloWorld\Controller;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $customerFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Demo\HelloWorld\Model\CustomerFactory $customerFactory
    ) {
        $this->customerFactory = $customerFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $customer = $this->customerFactory->create();
        //here you can call load or any other method
        //$customer->load(2);
        //then call your method
        $customer->demo();
    }
}

Upvotes: 2

Valery  Statichny
Valery Statichny

Reputation: 593

Just inject your model in controller's constructor and Objectmanager will do all job for you. This should look like this:

<?php
namespace Demo\HelloWorld\Controller;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $customerModel;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Demo\HelloWorld\Model\Customer $customerModel
    ) {
        $this->customerModel = $customerModel;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->customerModel->demo();
    }
}

Upvotes: 1

Related Questions