klein / klein.php

A fast & flexible router
MIT License
2.66k stars 290 forks source link

Central callback/hook before route response is called #405

Open felixWackernagel opened 4 years ago

felixWackernagel commented 4 years ago

Each of my routes start with the locale.

$klein->respond( '/', function ($request, $response, $service, $app) {
    $response->redirect( '/en/' );
});
$klein->with('/[*:locale]', function () use ($klein) {
    $klein->respond( 'GET', '/', [HomeController::class, 'get'] );
    $klein->respond( 'GET', '/foo', [FooController::class, 'get']);
});

For rendering i used twig and all information for twig is stored inside a service array called context.

$klein->respond( function ( $request, $response, $service, $app ) {
    $app->context = [
        'pageTitle' => 'Demo Site',
    'locale' => $request->locale
    ];
});

But at time of context initialization is locale null. When my callable of the respond-function is called only then is $request-locale available. I tried different approaches but everytime is locale not available.

rekcuFniarB commented 4 years ago

I'd try

$klein->respond( function ( $request, $response, $service, $app ) {
    $app->register('context', function() use ($request) {
        // Lazy  init
        return [
            'pageTitle' => 'Demo Site',
        'locale' => $request->locale
        ];
    });
});