【问题标题】:Symfony2 components, class instancesSymfony2 组件,类实例
【发布时间】:2014-03-29 16:52:17
【问题描述】:

问题是为什么

$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 ツ,但是如果我想在 ma​​tcher 中使用 route_collection 该怎么办

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

【问题讨论】:

    标签: php symfony symfony-components


    【解决方案1】:

    如果你想通过 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');
    

    【讨论】:

      【解决方案2】:

      当然,您的服务是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');
      

      【讨论】:

      • 谢谢你,我更新了一点问题,问题是我想用“matcher”服务来使用这一切,也许你知道如何通过配置解决这个问题?跨度>
      • 通过php而不是yaml进行配置?
      • 呵呵,得出了同样的结论,大约20分钟前完成了迁移到php :) 谢谢你的帮助!
      猜你喜欢
      • 1970-01-01
      • 2014-05-29
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多