0

问题是为什么

$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');

这里$routes_collectionSymfony\Component\Routing\RouteCollection的一个实例,并且这段代码运行良好。

和这里

# 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_collectionSymfony\Component\Routing\Loader\YamlFileLoader的一个实例,如果我将它与Symfony\Component\Routing\Matcher\UrlMatcher 一起使用,我会得到:

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.

更新

@Pazi ツ,但是如果我想在matcher中使用route_collection 怎么办

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

2 回答 2

2

如果要通过 config 获取 route_collection,则需要将 route_collection yaml_file_loader 定义为 route_collection 的工厂服务:

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

yaml_file_loader:
  class: Symfony\Copmonent\Routing\Loader\YamlFileLoader
  arguments: [ "@file_locator" ]

route_collection:
  class: Symfony\Component\Routing\RouteCollection
  factory_service: yaml_file_loader
  factory_method: load
  arguments: [ 'routes.yml' ]

这样你就可以做到

$routes_collection = $container->get('route_collection');
于 2014-05-29T12:26:44.813 回答
1

当然,您的服务是一个实例,YamlFileLoader因为您在class属性中配置了它。方法的返回值calls不影响实例类型。如果要获取返回值,则必须在 php 中调用该方法。

# 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');
于 2014-03-29T17:11:11.430 回答