I am using Klein php routing for a simple app
the documentation is ok for using the library, however it is not good at how to implement the views
for instance I want to display a flash message on success/error/warning etc
i understand how klein can store the flash like this error message in documentation
$klein->respond(function ($request, $response, $service, $app) use ($klein) {
// Handle exceptions => flash the message and redirect to the referrer
$klein->onError(function ($klein, $err_msg) {
$klein->service()->flash($err_msg);
$klein->service()->back();
});
so for my success message i did this
$service->flash("Success", $type = 'success' );
but other than foreach on the $_SESSION __flash, i cannot see how to implement this in my view
i surely think there is a render() or something i am missing...i mean otherwise why call all this when i can just store my own msg in a session, doesnt make much sense to me
anyways, any help is always appreciated
If you look at the docs for the latest version, there is a method Klein\ServiceProvider::flashes()
:
http://chriso.github.io/klein.php/docs/classes/Klein.ServiceProvider.html#method_flashes
The docs say it retrieves and clears all the flash messages, or all the flash messages of a given type.
This is not to be confused with Klein\ServiceProvider::flash()
, which adds a flash message:
http://chriso.github.io/klein.php/docs/classes/Klein.ServiceProvider.html#method_flashes
Here's the source:
https://github.com/chriso/klein.php/blob/master/src/Klein/ServiceProvider.php#L179
It looks like it returns an array of flashes, grouped by type, so you could foreach and echo them. If you're using the Klein templating system (in your case, you would render the template with $klein->service->render($myTemplateName))
, then you can call the ServiceProvider from the template as $this.
So in your template, you would have something like:
<? foreach($this->flashes() as $type=>$messages): ?>
<? foreach($messages as $msg): ?>
<div class="alert alert-<?= $type ?>"><?= $msg ?></div>
<? endforeach; ?>
<? endforeach; ?>
Obviously, you don't have to use the alternate control structure syntax, but I like to use it in my templates. It was part of the coding standard at a dev shop where I worked, and I adopted it as my own.
Just a heads up. The docs seem to represent the code in dev-master, rather than the 2.0.x branch they tell you to use on the GitHub page. A lot of code seems to have been moved around since then (at least we know it's not abandoned, right?). I found the dev-master branch to be much less broken.