Mohamed Ben HEnda
Mohamed Ben HEnda

Reputation: 2776

Can disabling autowiring and using annotation instead for services in Symfony 3?

In the DI there is Autowiring, annotation definition and PHP definition.

In Symfony 3.3 the autowiring is enabled by default. So if I disable the autowiring, can I use the annotation to define a service?

class Foo
{
    /**
     * @Inject({"my.specific.service"})
     */
    public function __construct(Bar $param1)
    {
    }
}

Update : Use JMSDiExtraBundle

namespace MediaBundle\Net;

use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Service;

/**
 * @Service("some.service.id", public=false, environments = {"prod", "test", "dev"})
 */
class Foo
{
    private $em;
    private $session;

    /**
     * @InjectParams({
     *     "em" = @Inject("doctrine.orm.entity_manager"),
     *     "session" = @Inject("session")
     * })
     */
    public function __construct($em, $session)
    {
        $this->em = $em;
        $this->session = $session;
    }
}

Calling the service in the controller:

namespace MediaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DefaultController extends Controller
{
    /**
     * @Route("/media")
     */
    public function indexAction()
    {
        $someService = $this->get('some.service.id');

        return $this->render('MediaBundle:Default:index.html.twig');
    }
}

Result : You have requested a non-existent service "some.service.id".

Upvotes: 3

Views: 2761

Answers (1)

leberknecht
leberknecht

Reputation: 1714

Is your service injected somewhere? If not, it will be dropped from the container due to public=false, see http://symfony.com/blog/new-in-symfony-3-2-improved-private-services

Upvotes: 4

Related Questions