Search code examples
phpsymfonysymfony-components

Symfony2 components, class instances


Question is why

$config = array(__DIR__ . '/app/config');
$locator = new Symfony\Component\Config\FileLocator($config);
$loader = new Symfony\Component\Routing\Loader\YamlFileLoader($locator);
$routes_collection = $loader->load('routes.yml');

Here $routes_collection is an instance of Symfony\Component\Routing\RouteCollection, and this code works fine.

And here

# config.yml
file_locator:
    class:    Symfony\Component\Config\FileLocator
    arguments:  ['%app_root%/app/config']

route_collection:
    class:    Symfony\Component\Routing\Loader\YamlFileLoader
    arguments: ["@file_locator"]
    calls:
              - [load, ['routes.yml']]

#app.php
$routes_collection = $container->get('route_collection')

$routes_collection is an instance of Symfony\Component\Routing\Loader\YamlFileLoader and if i use it with Symfony\Component\Routing\Matcher\UrlMatcher am getting:

Argument 1 passed to Symfony\Component\Routing\Matcher\UrlMatcher::__construct() must be an instance of Symfony\Component\Routing\RouteCollection, instance of Symfony\Component\Routing\Loader\YamlFileLoader given.

Update

@Pazi ツ, but how to be if i want to use route_collection in matcher

matcher:
    class:    Symfony\Component\Routing\Matcher\UrlMatcher
    arguments:  ["@route_collection", "@context"]

Solution

  • Of course your service is an instance of YamlFileLoader because you configured this in the class attribute. The return value of the methods calls doesn't influence the instance type. You have to call the method in php, if you want to get the return value.

    # config.yml
    file_locator:
        class:    Symfony\Component\Config\FileLocator
        arguments:  ['%app_root%/app/config']
    
    yaml_file_loader:
        class:    Symfony\Component\Routing\Loader\YamlFileLoader
        arguments: ["@file_locator"]
    
    #app.php
    $routes_collection = $container->get('yaml_file_loader')->load('routes.yml');