2016-08-19 3 views
1

würde ich diese Art von URLs Routing mag:Silex 2: Deklarieren {_locale} optional in Routings

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

Ich habe diese Controller-Klasse erstellt:

<?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); 
    } 
} 

Und es hat in dieser registriert übrigens:

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

diese URL funktioniert gut:/hallo/foo Aber dieses nicht:/en/hallo/foo, th wird Fehler angezeigt:

NotFoundHttpException in RouterListener.php Linie 125: Keine Route für "GET/en/hallo/foo /"

Es scheint, dass die zweite "mount" Satz gefunden ist auf den ersten überschrieben.

Kann mir jemand bei diesem Problem helfen? Wie kann ich Routing mit optionalem {_locale} festlegen?

Danke.

Antwort

0

Ich hatte das gleiche Problem und schrieb Dienstanbieter, die automatisch Gebietsschema zu allen Routen https://github.com/pmaxs/silex-locale hinzugefügt. Vielleicht erfüllt es Ihre Anforderungen.

+0

Danke für Ihre schnelle Antwort :) Ihre Bibliothek funktioniert gut und es beschwert fast meine Anforderungen. Eine Sache: Wenn meine verfügbaren Sprachen "es" sind, "en", ist es möglich, wenn die geladene URL "/ fr/hallo/foo" anstelle von NotFoundHttpException ist, redirect (301) auf den Standard "/ en/hallo/foo "oder"/Hallo/Foo "? – cybtow

+0

Sie können 'fr' als mögliches Gebietsschema hinzufügen und in middlware' $ app-> vorher umleiten (Funktion (\ Symfony \ Component \ HttpFoundation \ Request $ Anfrage) { if ($ request-> getLocale() == 'fr') redirect ...; }); ' –

+0

Danke für Ihre Hilfe! – cybtow