Symfony 2 Service Container Zero

I am new to Symfony 2 and trying to create a simple application to learn. I created a package GoogleApiBundle. Inside the bundle, I have a controller YouTubeControllerthat is a service:

//services.yml
service:
    myname_googleapi_youtube:
        class: Myname\GoogleApiBundle\Controller\YouTubeController

In another package, I'm trying to call a function in YouTubeController

//anotherController.php
$service = $this->get('myname_googleapi_youtube');
$result = $service->getResultFunction();

//YouTubeController.php
public function getResultFunction()
{
    $parameter = $this->container->getParameter('a');
    //...
}

Then I get an exception FatalErrorException: Error: Call to a member function getParameter() on a non-object ...because there $this->containeris NULL.

I searched but received no answer. Am I doing wrong?

+4
source share
1 answer
//services.yml
service:
    myname_googleapi_youtube:
        class: Myname\GoogleApiBundle\Controller\YouTubeController
        arguments: [@service_container]

And you will have:

<?php

namespace Myname\GoogleApiBundle\Controller

use Symfony\Component\DependencyInjection\ContainerInterface;

class YouTubeController
{
    /**
    * @param ContainerInterface $container
    */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
    * Obtain some results
    */
    public function getResultFunction()
    {
        $parameter = $this->container->getParameter('a');
        //...
    }

    /**
    * Get a service from the container
    *
    * @param string The service to get
    */
    protected function get($service)
    {
        return $this->container->get($service);
    }
}

This practice is very controversial, so I would recommend that you read quickly:

+5
source

All Articles