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.
Related
I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example:
A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpage so I know how to travel through $result from my View.
A form POST a $request to a Controller, I use pr($request) to see what is sending in before processing it in the Controller. The content of $request will be displayed immediately on the webpage right after I hit Submit the form.
I'm wondering if I could do the same thing in django instead of going to the shell and try pprint (or could I just use pprint to print out to the web???)
This is a really simple example about what I'm talking about:
app_name/views.py:
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
return render(request, 'socs/detail.html', {'soc': soc})
How can I just view clearly what is in "soc". In cakephp, I could just pr($soc) right there and it will be displayed right on the detail.html page.
I have tried this and it didn't work (I'm sure it's basic but i'm just new to this)
import pprint
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
pprint.pprint(soc)
return render(request, 'socs/detail.html', {'soc': soc})
I have spent two days doing research but I couldn't find the answer. I'm hoping one of you can help this newbie out.
The way you're trying to print will show the print in the terminal that is running your Django server. If you just need to see it quick, check there.
If you want to output the value on to the rendered page, you'll have to include it in the template using template tages. It looks like you send {'soc': soc} to your template as context. Because of this, you should be able to use it in your template. So, in your template (socs/detail.html), just add {{ soc }} somewhere and it should print out the value. The template has full access to the object, so if you wanted something specific, you can also print that instead (like {{ soc.id }}).
If you want to see everything that's in the object without specifying all of the different fields yourself, send OBJECT.__dir__. For example, for this you'd send {'soc': soc.__dir__} as your context. Keep in mind that this likely should not be used for anything but inspection on your part.
If you'd like to learn more about Django's templating, check out the syntax and more.
I am slightly confused as to what the best method is of handling redirecting and displaying error/ success messages using an MVC framework, specifically Kohana.
I have a Controller User which extends the Base controller.
Am am trying to use the action_remove() function in the base controller then redirect back to the page they were on and display a message 'User has been removed....'
I don't want to pass the error message in the GET params. Is there a standard way of doing this?
You should try to use flash session data. It is very useful when You want to show errors as well as messages. At first access flash data is removed so it can be accessed only once.
http://docs.kohanaphp.com/libraries/session#flash_session_data
Also there was some related post about this here Which is the best way to display 'flash messages' in kohana v3?
You can use Message Modules in kohana 3.x. its used to display messages.
please download this module it from here and extract . Then paste it in modules folder.
https://github.com/GoldCoastMedia/kohana-flash
Then enable it in applications/bootstrap.php like as follows.
'message' => MODPATH.'message',
There are 5 type of messages are available. success, error, warning, info, notice. You can give styles for each messages . but you need to write class in the same name of message type.
Message::error('pls login to access');
//to assign message type.its error message.
echo Message::display();
//to display it
thats it. but remember that you need to create class in the name of success, error, warning, info, notice to apply styles.
to check condition in view file , you can use it.
$sucessful_message=Message::display();
if($sucessful_message) { ?>
<div id="messagedisplay" class="padding_150">
<div class="notice_message">
<?php echo $sucessful_message; ?>
</div>
</div>
<?php } ?>
I am looking to manipulate the $session->flash() output in my CakePHP app, Currently I have the very simple default implementation of showing flash and auth error messages:
<?php
$session->flash();
$session->flash('auth');
?>
This produces a <div> with an ID and class that has the message inside. What I would like to do is wrap/replace the generated HTML, specifically with some jQuery UI classes, but wrapping is difficult as I am unable to tell when there is actually a message going to be displayed so I end up with an empty but style error div. What I really need for wrapping to work is to check in $session->flash() returns anything, but I get 'can't use method return value in write context' when checking it with empty();
As far as I can tell the generated HTML is hard coded into the session helper! Bonus points if you can work out how to change the class on the auth message and normal flash message independently.
To check if a message is going to be flashed, put this in the layout
<?php if($session->check('Message')){ echo $this->Session->flash();} ?>
CSS attributs can be set when you set the message to be flashed
http://book.cakephp.org/view/1311/Methods#setFlash-1313
read up on setFlash() and use the other params that the method takes to define your own elements. you can then do what ever you like.
http://book.cakephp.org/view/400/setFlash
A work-around solution I have found is to set $session->flash() to a variable and then check it with empty() so I can echo out the appropriate <div> if necessary.
$flashMessage = $this->flash();
$authMessage = $this->flash('auth');
.. and then check if each one is empty. Of course I have some unnecessary html inside there but as far as the auth message goes, I think this is as flexible as I can get.
I've experienced first hand the extent of the horror and foot-shooting that the ugliness of PHP can cause. I'm onto my next project (you may be wondering why I'm not just switching languages but that's not why I'm here) and I've decided to try doing it right, or at least better, this time.
I've got some models defined, and I've started on a main controller. I'm at a fork in my decisions about how to implement the view. So far, the main controller can be given lists of display functions to call, and then it can spew out the whole page with one call. It looks like:
function Parse_Body()
{
foreach ($this->body_calls as $command)
{
$call = $command['call'];
if (isset($command['args'])) $call($command['args']);
else $call();
}
}
My dilemma is this:
Would it be better to have all of my display functions return the HTML they generate, so that the main controller can just echo $page; or should the display files use raw HTML outside of PHP, which gets output as soon as it's read?
With the former, the main app controller can precisely control when things get output, without just relinquishing complete control to the whim of the displays. Not to mention, all those lists of display functions to call (above) can't really be executed from a display file unless they got passed along. With the latter method, I get the benefit of doing HTML in actual HTML, instead of doing huge PHP string blocks. Plus I can just include the file to run it, instead of calling a function. So I guess with that method, a file is like a function.
Any input or advice please?
Would it be better to have all of my
display functions return the HTML they
generate, so that the main controller
can just echo $page; or should the
display files use raw HTML outside of
PHP, which gets output as soon as it's
read?
One of the advantages of php is that the processing is similar to the output:
So:
<h1> <?= $myHeading; ?> </h1>
Is more clear than:
echo "<h1>$myHeading</h1>";
An even more than:
echo heading1($myHeading); //heading1() being an hypothethical user defined function.
Based on that I consider that it is better to in the view to have HTML and and just print the appropriate dynamic fields using php.
In order to get finner control over the output you can use: ob_start as gurunu recommended.
You could of course use any of the several php MVC frameworks out there.
My prefered one, now is: Solarphp
but Zend Framework and Cakephp could help you too.
And finally if you don't want to use any framework
You could still use a pretty slim templating engine: phpSavant.
That will save you a few headaches in the development of your view.
th
You can get the benefit of both, obtaining a string of HTML while also embedding HTML within PHP code, by using the output control functions:
From the PHP manual # http://www.php.net/manual/en/ref.outcontrol.php:
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
First buffer everything. then replace tags using a parser at end of script.
<?php
$page_buffer = '';
function p($s){
global $page_buffer;
$page_buffer .= $s;
}
$page_buffer = str_replace(
array('<$content$>','<$title$>'),
array($pagecontent,$pagetitle),
$page_buffer);
echo $page_buffer;
?>
Samstyle PHP Framework implements output buffering and View model this way
And did I mention about benefits of buffering your output in a variable before "echo-ing"? http://thephpcode.blogspot.com/2009/02/php-output-buffering.html
How can I implement jquery in my Zend Framework application in a custom manner.
appending jquery.js ok
appending script ok
send POST data to controller ok
process POSTed data ok
send 'AjaxContext' respond to client now ok (thanks)
I'm using jquery for the first time, what am I doing wrong?
Early on, the best practice to get Zend to respond to ajax requests without the full layout was to check a variable made available via request headers. According to the documentation many client side libraries including jQuery, Prototype, Yahoo UI, MockiKit all send the the right header for this to work.
if($this->_request->isXmlHttpRequest())
{
//The request was made with via ajax
}
However, modern practice, and what you're likely looking for, is now to use one of two new helpers:
ContextSwitcher
AjaxContent
Which make the process considerably more elegant.
class CommentController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('view', 'html')
->initContext();
}
public function viewAction()
{
// Pull a single comment to view.
// When AjaxContext detected, uses the comment/view.ajax.phtml
// view script.
}
Please Note: This modern approach requires that you request a format in order for the context to be triggered. It's not made very obvious in the documentation and is somewhat confusing when you end up just getting strange results in the browser.
/url/path?format=html
Hopefully there's a workaround we can discover. Check out the full documentation for more details.
Make sure your using $(document).ready() for any jQuery events that touch the DOM. Also, check the javascript/parser error console. In Firefox it's located in Tools->Error Console. And if you don't already have it installed, I would highly recommend Firebug.
This should have been a comment, can't, yet...
It has nothing to do with ZF+Jquery combination.
First try a proto of what you need with a simple php file. No framework, just Jquery and straight forward, dirty php.
Oh, and don't forget to track what happens with FireBug.