Symfony2 How to use parameters.yml in controller as variable

I am working with a Symfony2 project.

I am trying to pice data, decleared in parameters.yml, and use that data in one of my controllers.

I read this one in the Symfony2 documentation about getParameters()

but it doesn't work.

In my .yml options, I did this:

sitemap_root_url: http:/example.co.uk/news/

      

In my controller, I am trying to do this:

$this->test = $this->container->getParameters('sitemap_root_url');

      

This is the error I am getting:

Notice: Undefined property $container

      

+3


source to share


4 answers


Try $this->container->getParameter('sitemap_root_url');

This works well for me, I am using Symfony 2.5.

If you want to use a container in your controller you can extend

Symfony \ Bundle \ FrameworkBundle \ Controller \ Controller (Basic Symfony Controller).



// src/AppBundle/Controller/HelloController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class HelloController extends Controller
{
    // ...
}

      

Then you can get your property. Example controller that works for me:

namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Response

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class HelloController extends Controller
{
    public function indexAction()
    {
            return new Response(
                    $this->container->getParameter('sitemap_root_url');
            );
    }
}

      

+2


source


Apparently $container

not declared in your controller, if you want to access the controller you can extend Symfony\Bundle\FrameworkBundle\Controller\Controller

and then use$this->container->getParameter('sitemap_root_url')



Otherwise, you will have to declare the controller as a service and inject the container.

+2


source


Hi I have to answer (I wanted to edit the first answer), but you have unnecessary s in getParameters()

, that's all the problems I am thinking about;)

+1


source


for symfony 2.6

$this->container->getParameter('api_key'); 

      

above symfony 2.6

$this->getParameter('api_key');

      

0


source







All Articles