3

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

4
  • I added. tks @RajeevKTomy
    – Lino
    Aug 13, 2015 at 7:25
  • @PaW You added your answer with your question itself. That is not what I intended.You should put that as answer, you can find a button "add an answer" below. Paste your answer in that text area and click on that button :) Aug 13, 2015 at 7:27
  • Answer: $this->_objectManager->get('Full\Model\Class\Name\Here'); (as getSingleton() in Magento 1.x) or $this->_objectManager->create('Full\Model\Class\Name\Here'); ( as getModel() in Magento 1.x). Thanks @RajeevKTomy for advice !
    – Lino
    Aug 13, 2015 at 7:36
  • @PaW Dont worry I did that for you. Aug 13, 2015 at 7:41

3 Answers 3

10

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().

3

To begin, I would follow this tutorial https://www.ashsmith.io/2014/12/simple-magento2-controller-module/ to create a simple controller to add some content. From there, I added

Demo/Simple/Model/Customer.php

<?php
namespace Demo\Simple\Model;
use Magento\Framework\Object;

class Customer extends Object
{
    public function sayHi(){
        echo "HEYHO";
    }
}

And then added a new dependency via Constructor injection in the Controller:

\Demo\Simple\Model\Customer $customer

So now my Demo/Controller/Index/Index.php looks like:

<?php
namespace Demo\Simple\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
     protected $resultPageFactory;

    /**
     * @var \Demo\Model\Customer
     */
        protected $customer;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory     resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
         \Demo\Simple\Model\Customer $customer
    )
    {
        $this->resultPageFactory = $resultPageFactory;
        $this->customer = $customer;
        parent::__construct($context);
    }

    /**
     * Default customer account page
     *
     * @return void
     */
    public function execute()
    {
        $this->customer->sayHi();
        return $this->resultPageFactory->create();
    }
}

And, after clearing all caches, this is echoing "HEYHO" at the top of my page.

1
  • Your code helped me but there is an error in model file (Demo/Simple/Model/Customer.php): class Customer extends \Magento\Framework\Object; this class does not exist (Magento 2.1.2) I've used class Customer extends \Magento\Framework\Model\AbstractModel and all worked fine
    – WaPoNe
    Dec 22, 2016 at 9:01
0

enter image description here

in Model/Method/customFree.php

    <?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Payment\Paypal\Model\Method;
/**
 * Free payment method
 * @method \Magento\Quote\Api\Data\PaymentMethodExtensionInterface getExtensionAttributes()
 */
class customFree extends \Magento\Payment\Model\Method\Free
{


    /**
     * Check whether method is enabled in config
     *
     * @param \Magento\Quote\Model\Quote|null $quote
     * @return bool
     */
    public function isAvailableInConfig2()
    {
        echo "  learning magento2  ";
    }
}

In controller/Index/Index.php

<?php

namespace Payment\Paypal\Controller\Index;
use \Magento\Framework\App\Action\Action as controllerAction; 
class Index extends controllerAction {  

     protected $customer;

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

        parent::__construct($context);
    }

    /**
     * Sets the content of the response
     */
    public function execute() {
        $this->getResponse()->appendBody('Hello world');
        $this->customer->isAvailableInConfig2();
    }
}

in etc/frontend/routes.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="Payment" frontName="custompaypal">
            <module name="Payment_Paypal" />
        </route>
    </router>
</config>

in browser

localhost/magento/custompaypal

enter image description here

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.