klein/klein.php

Tutorial

AAB94 opened this issue · 6 comments

Hi,
just wondering if there are any tutorials for this library.
I wanna use it to filter users as that is allow user access to a page based on his session.
can you show some examples as to how your library works

If I find time, I'll create an "examples" page in the wiki, with a user authentication section. However, if you just need some code to get you started:

$klein = new Klein\Klein();

$klein->respond('/unauthorised', function () {
    return 'You do not have access to this page!';
});

$klein->with('/admin', function () use ($klein) {

    // this will be run when anyone 
    // navigates to a route beginning
    // with "/admin".
    $klein->respond(function ($request, $response) {
        $hasAccess = Auth::isAuthorized();

        // redirect if not authorized
        if ( ! $hasAccess) {
            $response->redirect('/unauthorized');
        }
    });

    $klein->respond('/?', function () {
        return 'Admin Home Page!';
    });
});

$klein->dispatch();

This code is untested.

Instead of redirecting, it might be better to use $klein->abort(403), and set up a 403 block in the onHttpError handler:

$klein->with('/admin', function () use ($klein) {
    $klein->respond(function ($request, $response) use ($klein) {
        if( !Auth::isAuthorized()) {
            $klein->abort(403); // 403 = Forbidden
        }
    }
}

$klein->onHttpError(function ($code, $router) {
    switch ($code) {
        case 403:
            $router->response->body('You do not have access to this page!');
    }
}

I do wish the abort method were on the $response object instead of the $klein object, though.

Nice catch. :) I keep forgetting about the onHttpError() handler.

In onHttpError(), is there a way to access $app?

$klein->onHttpError(function ($code, $router) {
    $app = $router->app();
});

That works, thanks @nbish11