xfra35 / f3-multilang

Create multilingual apps with this localization plugin for the PHP Fat-Free Framework
GNU General Public License v3.0
48 stars 13 forks source link

Usage with f3-middleware #20

Closed ursulnegrul closed 5 years ago

ursulnegrul commented 5 years ago

Seems both rewrite the $f3->ROUTES and can't figure which one to load and run first, not mention i'm also using f3-events, my project starts to turn into a mess. Seems I have to use the full route with language for middleware to detect.. \Middleware::instance()->before('GET /en-GB/user'.. Moving the \Multilang initialization before/after/between the middleware on/run has no effect.

xfra35 commented 5 years ago

Actually f3-middleware doesn't rewrite routes. $middleware->run() executes some code according to the current URI, just like $f3->run() does.

So it doesn't matter if you're running it after or before Multilang. What does matter is that Multilang rewrites URIs so your whole application should be aware of that, including the Middleware plugin.

That means the Middleware hooks should include the language part of the URI.

See:

$f3=Base::instance();

// set routes
$f3->route('GET /foo','App->foo');
$f3->route('GET /bar','App->bar');

// define multilang behaviour
$f3->set('MULTILANG.languages',[
  'fr'=>'fr-FR,fr',
  'it'=>'it-IT,it',
]);
Multilang::instance();

// define Middleware hooks
$mw=Middleware::instance();
$mw->before('GET /@lang/foo',function(){
  echo 'before foo (any language)';
});
$mw->before('GET /it/foo',function(){
  echo 'before foo (italian)';
});
$mw->after('GET /@lang/foo',function(){
  echo 'after foo (any language)';
});

// run router & hooks
$mw->run('before');
$f3->run();
$mw->run('after');

NB: the @lang token is internal to the Middleware plugin.

ursulnegrul commented 5 years ago

Thank you for the example, I noticed too.