Silex 2:在路由中声明 {_locale} 可选

Silex 2: Declare {_locale} optional in routings

我想路由这些 URLs:

/hello/{name}
/en/hello/{name}
/es/hello/{name}

我已经创建了这个控制器class:

<?php

namespace Fw\Controllers;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Fw\Application as FwApplication;

class Hello implements ControllerProviderInterface {

    const URL_BASE = '/hello';
    const URL_BASE_LOCALE = '/{_locale}/hello';

    public function connect(Application $app) {
        $controllers = $app['controllers_factory'];

        $controllers
                ->get('/{name}/', array($this, 'nameAction'))
                ->bind('hello_name')
        ;

        return $controllers;
    }

    public function nameAction(FwApplication\ApplicationBase $app, Request $request, $name) {
        return new Response('Hello ' . $name, 200);
    }
}

并且是这样注册的:

$app->mount(FwControllers\Hello::URL_BASE_LOCALE, new FwControllers\Hello());
$app->mount(FwControllers\Hello::URL_BASE, new FwControllers\Hello());

这个URL效果不错:/hello/foo 但是这个不是:/en/hello/foo,显示这个错误:

NotFoundHttpException in RouterListener.php line 125: No route found for "GET /en/hello/foo/"

好像第二句"mount"被第一句覆盖了

谁能帮我解决这个问题?如何使用可选的 {_locale} 设置路由?

谢谢。

我遇到了同样的问题并编写了自动将语言环境添加到所有路由的服务提供商 https://github.com/pmaxs/silex-locale。说不定能满足你的要求。