2

I have a problem when I try to create a service in Symfony2.

This is my services.yml

services:
    Menu:
        class:  My\WebBundle\Classes\System\Menu        
        arguments: [@service_container]

This is my service Menu:

namespace My\WebBundle\Classes\System;

use Symfony\Component\DependencyInjection\ContainerInterface as Container;

Class Menu{
    private $container;

    public function __construct(Container $container) {                
        $this->container = $container;                
    }

    public function getMenu($section) {
        return "hello";
    }
}

When in a controller I do:

$menu = $this->get('Menu');

I get:

FatalErrorException: Error: Cannot instantiate interface My\WebBundle\Classes\System\Menu in ...\cache\dev\appDevDebugProjectContainer.php line 1522

Of course I cleaned cache.

1 Answer 1

2

Change your use statement to;

use Symfony\Component\DependencyInjection\Container;

Also I would redeclare the arguments enclosing the service name in quotes.

services:
    Menu:
        class:  My\WebBundle\Classes\System\Menu        
        arguments: ["@service_container"]

I would question why you are injecting the whole container though.
Why not just inject the parts you need?

If you are defining your controller as a service also, you can access your Menu service by injecting that into your controller.

EXTRA AS PER COMMENT REQUEST;

services:
        Menu:
            class:  My\WebBundle\Classes\System\Menu        
            arguments: ["@router"]

And class would look like;

<?php 
namespace My\WebBundle\Classes\System;

use Symfony\Component\Routing\RouterInterface;

Class Menu{
    private $router;

    public function __construct(RouterInterface $router) {                
        $this->router = $router;                
    }

    public function getMenu($section) {
        return "hello";
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thansk, I only need to user router generate, to can use $this->get('router'). What part I need to inject?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.