Php – Argument 1 passed to __construct must be an instance of Services\ProductManager, none given

PHPsymfonytwig

in service.yml

test_product.controller:
        class: MyBundle\Controller\Test\ProductController
        arguments: ["@product_manager.service"]

in controller

class ProductController extends Controller
{
     /**
     * @var ProductManager
     */
    private $productManager;

    public function __construct(ProductManager $productManager){
        $this->productManager = $productManager;
    }
}

in routing.yml

test_product_addNew:
    path: /test/product/addNew
    defaults: { _controller:test_product.controller:addNewAction }

I want to use ProductManger in contructor to do some stuff but it gives me this error

Catchable Fatal Error: Argument 1 passed to
MyBundle\Controller\Test\ProductController::__construct()
must be an instance of MyBundle\Services\ProductManager,
instance of Symfony\Bundle\TwigBundle\Debug\TimedTwigEngine given,
called in
…./app/cache/dev/appDevDebugProjectContainer.php
on line 1202 and defined

I am new to symfony, any help is appreciated

Best Answer

You have inverted the logical of services.

First, it's your manager wich must be defined as a service because it's it you will need to call from controller.

// services.yml
product_manager:
        class: MyBundle\Path\To\ProductManager

Then call directly your manager defined as a service in your controller.

// Controller
class ProductController extends Controller
{
     [...]
     $this->get('product_manager');
     [...]
}

And you do not need to overload __construct() methode. Only call ->get(any_service) where you need it.

Also your route is wrong. You have to define controller from is namespace.

// routing.yml
test_product_addNew:
    path: /test/product/addNew
    defaults: { _controller:MyBundle:Product:addNew }
Related Topic