utkarsh2k2
utkarsh2k2

Reputation: 1096

How do I read from a yml file in a controller in symfony2?

I have a random name.yml file inside lets say my src/AppBundle/Controller folder. The content inside the YML file is simple:

name: utkarsh

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

$name = $this->getName('name');

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

Attempted to call an undefined method named "getName" of class "AppBundle\Controller\DefaultController".

What is the correct way to do this?

Upvotes: 1

Views: 2757

Answers (2)

Alister Bulman
Alister Bulman

Reputation: 35149

If it's just going to be a general file, and wouldn't better be part of the framework's configuration (for example, in the parameters.yml file), you can parse/read the file using the Yaml component, which is already used by the Symfony framework.

use Symfony\Component\Yaml\Yaml;

$values = Yaml::parse(file_get_contents('/path/to/name.yml'));
echo $values['name'];

If the file you are loading is in the same directory as the code that is running it, you can use the PHP Automagic constants - __DIR__, file_get_contents(__DIR__ . '/name.yml'), or use it as a relative base to work from.

Upvotes: 2

Anjana Silva
Anjana Silva

Reputation: 9201

Don't just put your YML file in the Controllers folder. Instead, move your YML file into your bundles' config directory. See below,

AppBundle\Resource\config\abc.yml

Then, import this file in your services.yml file. See below,

imports:
    - { resource: abc.yml }

And, make sure you abc.yml file will have a structure like this,

parameters:
  name: utkarsh

Finally, you can access this parameter inside the Controller by calling like this,

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

I hope this helps :)

Cheers!

Upvotes: 2

Related Questions