ivoba
ivoba

Reputation: 5986

services.yml and path to file in same bundle

How do i refer to a data file in the services.yml, which is located in the same or any bundle?

Im shipping a csv-file which i would like to inject as argument.
It works when i use the direct path:

mybundle.data.csv: %kernel.root_dir%/../vendor/mybundle/my-bundle/mybundle/MyBundle/Resources/data/data.csv 

This is pretty verbose and unflexible and thus i am looking for a resolver like:

data.csv: "@MyBundle/Resources/data/data.csv"

But this is not working:

... has a dependency on a non-existent service "mybundle/resources/data/data.csv".

any ideas?

Upvotes: 4

Views: 3518

Answers (2)

user3026944
user3026944

Reputation: 129

@-escaping in yaml is supported now

https://github.com/symfony/symfony/issues/4889

You can use it like this

data.csv: "@@MyBundle/Resources/data/data.csv"

Upvotes: 4

Florian Eckerstorfer
Florian Eckerstorfer

Reputation: 1526

First of all: in the YAML service and parameter definitions @ also refers to another service. That is why your code does not work.

Basically you have two possibilities. The first and simple one is to use a relative path in your bundles services.yml and append it in your CSV class.

For example:

# src/Acme/DemoBundle/Resources/config/services.yml
parameters:
    data.csv: "Resources/data/data.csv"

In the class you want to read the CSV file:

// src/Acme/DemoBundle/Import/ReadCsv.php
...
class ReadCsv
{
    ...
    public function __construct($csvFile)
    {
       $this->csvFile = __DIR__.'/../'.$csvFile; 
    }
    ...
}

The other possibility is to make the filename of the CSV file configurable via config.yml (see this article in the Symfony2 cookbook) and insert a special placeholder in the config value that you replace in your AcmeDemoBundleExtension class:

// src/Acme/DemoBundle/DependencyInjection/AcmeDemoBundleExtension.php
...
public function load(array $configs, ContainerBuilder $container)
{
    ...
    $container->setParameter('acme_demo.csv_file', str_replace('__BUNDLE_DIR__', __DIR__'./.., $config['csv_file']);
}
...

Your config.yml would look like:

# app/config/config.yml
acme_demo:
    csv_file: __BUNDLE_DIR__/Resources/data/data.csv

Upvotes: 3

Related Questions