156

I have put a couple of custom variables in my app/config/parameters.yml.

parameters:
    api_pass: apipass
    api_user: apiuser

I need to access these from my controller, and have tried to fetch them with

$this->get('api_user');

from within my controller file. When I try this, I get this error message:

You have requested a non-existent service "api_user".

What is the correct way to do this?

Dharmang
  • 3,018
  • 35
  • 38
Bohr
  • 2,086
  • 3
  • 15
  • 19

8 Answers8

304

In Symfony 2.6 and older versions, to get a parameter in a controller - you should get the container first, and then - the needed parameter.

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

This documentation chapter explains it.

While $this->get() method in a controller will load a service (doc)

In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:

$this->getParameter('api_user');
Javier Eguiluz
  • 3,987
  • 2
  • 23
  • 44
Vitalii Zurian
  • 17,858
  • 4
  • 64
  • 81
  • 3
    Note that the `get` method in the controller uses the container too, but it can only get services from a container, not parameters. You need `getParameter` to get parameters. – Wouter J Dec 16 '12 at 12:55
  • When I try `$this->getContainer()->getParameter('api_user');` I get Fatal error: Call to undefined method ..Longpath..\Controller::getContainer(). – Bohr Dec 16 '12 at 13:49
  • 1
    @Bohr sorry, different version of Symfony2. I've edited my answer - check it now ;) – Vitalii Zurian Dec 16 '12 at 16:44
  • 2
    The URL for documentation is now http://symfony.com/doc/2.7/components/dependency_injection/parameters.html – SilvioQ Jun 09 '15 at 18:45
  • Symfony 2.7 and newer: `$this->hasParameter()` not working yet. – Saman Mohamadi Jul 28 '16 at 09:07
  • You can upgrade this instantly with Rector now: https://github.com/rectorphp/rector/pull/333 – Tomas Votruba Mar 03 '18 at 11:25
32

The Clean Way - 2018+, Symfony 3.4+

Since 2017 and Symfony 3.3 + 3.4 there is much cleaner way - easy to setup and use.

Instead of using container and service/parameter locator anti-pattern, you can pass parameters to class via it's constructor. Don't worry, it's not time-demanding work, but rather setup once & forget approach.

How to set it up in 2 steps?

1. app/config/services.yml

# config.yml

# config.yml
parameters:
    api_pass: 'secret_password'
    api_user: 'my_name'

services:
    _defaults:
        autowire: true
        bind:
            $apiPass: '%api_pass%'
            $apiUser: '%api_user%'

    App\:
        resource: ..

2. Any Controller

<?php declare(strict_types=1);

final class ApiController extends SymfonyController
{
    /**
     * @var string 
     */
    private $apiPass;

    /**
     * @var string
     */
    private $apiUser;

    public function __construct(string $apiPass, string $apiUser)
    {
        $this->apiPass = $apiPass;
        $this->apiUser = $apiUser;
    }

    public function registerAction(): void
    {
        var_dump($this->apiPass); // "secret_password"
        var_dump($this->apiUser); // "my_name"
    }
}

Instant Upgrade Ready!

In case you use older approach, you can automate it with Rector.

Read More

This is called constructor injection over services locator approach.

To read more about this, check my post How to Get Parameter in Symfony Controller the Clean Way.

(It's tested and I keep it updated for new Symfony major version (5, 6...)).

Tomas Votruba
  • 23,240
  • 9
  • 79
  • 115
  • New minimalistic way on this topic: https://www.tomasvotruba.cz/blog/2018/11/05/do-you-autowire-services-in-symfony-you-can-autowire-parameters-too/ – Tomas Votruba Nov 12 '18 at 11:27
12

I send you an example with swiftmailer:

parameters.yml

recipients: [email1, email2, email3]

services:

your_service_name:
        class: your_namespace
        arguments: ["%recipients%"]

the class of the service:

protected $recipients;

public function __construct($recipients)
{
    $this->recipients = $recipients;
}
xarlymg89
  • 2,552
  • 2
  • 27
  • 41
Gravitty
  • 131
  • 1
  • 2
11

In Symfony 4, you can use the ParameterBagInterface:

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MessageGenerator
{
    private $params;

    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    public function someMethod()
    {
        $parameterValue = $this->params->get('parameter_name');
        // ...
    }
}

and in app/config/services.yaml:

parameters:
    locale: 'en'
    dir: '%kernel.project_dir%'

It works for me in both controller and form classes. More details can be found in the Symfony blog.

lxg
  • 12,375
  • 12
  • 51
  • 73
Ghazaleh Javaheri
  • 1,829
  • 19
  • 25
  • 1
    Passing whole parameters bag is like passing a whole container. It makes sense only in "if some particular service needs lots of container parameters" (quoted from the post) – Tomas Votruba Jan 02 '19 at 12:58
  • so ,are you mean passing whole parameter cause problem in performance? – Ghazaleh Javaheri Jan 05 '19 at 12:06
  • That's one of reasons, but mostly for readability. If I see parameter name `$meetupApiKey` I know what to expect slightly better than in `$parameterBag` – Tomas Votruba Jan 05 '19 at 13:15
2

You can use:

public function indexAction()
{
   dump( $this->getParameter('api_user'));
}

For more information I recommend you read the doc :

http://symfony.com/doc/2.8/service_container/parameters.html

mrDjouk
  • 271
  • 5
  • 8
2

In Symfony 5 when your Controller extends AbstractController you can use :

$projectDir = $this->getParameter('kernel.project_dir');

See https://symfony.com/doc/current/configuration.html#accessing-configuration-parameters for more info

Toothgip
  • 469
  • 6
  • 14
1

In Symfony 4.3.1 I use this:

services.yaml

HTTP_USERNAME: 'admin'
HTTP_PASSWORD: 'password123'

FrontController.php

$username = $this->container->getParameter('HTTP_USERNAME');
$password = $this->container->getParameter('HTTP_PASSWORD');
Achraf JEDAY
  • 1,936
  • 5
  • 24
  • 33
-1

You can also use:

$container->getParameter('api_user');

Visit http://symfony.com/doc/current/service_container/parameters.html

COil
  • 7,201
  • 2
  • 50
  • 98
Atikrant Upadhye
  • 185
  • 2
  • 13