2014-03-29 45 views
0

問題是,爲什麼Symfony2的組件,類實例

$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 \分量\路由\ 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 \分量\路由\裝載機\實例YamlFileLoader,如果我用它來與的Symfony \分量\路由\匹配器\ 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"] 

回答

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'); 
+0

感謝你爲這個,我更新了一點問題,問題是我想用「匹配器」服務使用所有這些,也許你有想法如何通過配置解決這個問題? – MyMomSaysIamSpecial

+0

通過php而不是yaml進行配置嗎? –

+0

呵呵,得出了同樣的結論,並在20分鐘前完成了對php的遷移:)感謝您的幫助! – MyMomSaysIamSpecial

2

如果你想通過配置採取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');