问题是为什么
$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_collection 是 Symfony \ 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_collection 是 Symfony \ 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ツ,但如果我想在匹配器
中使用 route_collection ,该怎么办?matcher:
class: Symfony\Component\Routing\Matcher\UrlMatcher
arguments: ["@route_collection", "@context"]
答案 0 :(得分: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');
答案 1 :(得分: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');