Kohana framework - Ajax implementation best practices
I am developing an application in Kohana framework. I would like to know the best practices in implementing ajax in kohana. So far I am using different controller for ajax. I think the important concerns will be minimizing the resources requirement and handl开发者_如何学JAVAing sessions.
Thanks in advance
I'm using this:
In Controller_Template:
public function before()
{
$this->auto_render = ! $this->request->is_ajax();
if($this->auto_render === TRUE)
{
parent::before();
}
}
And inside my actions:
if ($this->request->is_ajax())
{
...
$this->response->headers('Content-type','application/json; charset='.Kohana::$charset);
$this->response->body($jsonEncoded);
}
As the fellas above said, you don't need a separate controller for your ajax actions. You may take advantage of Kohana's request object to identify the request type. This may be done in the following way:
<?php
class Controller_Test extends Controller_Template {
/**
* @var View Template container
*/
protected $template = 'template';
/**
* @var View Content to render
*/
protected $content = 'some/content/view';
// Inherited from parent class
protected $auto_template_render = TRUE;
public function before()
{
parent::before();
if ($this->request->is_ajax() OR !$this->request->is_initial()) {
$this->auto_template_render = FALSE;
}
}
public function after()
{
if ($this->auto_template_render == FALSE) {
// We have ajax or internal request here
$this->template = $this->content;
} else {
// We have regular http request for a page
$this->template = View::factory($this->template)
->set('content', $this->content);
}
// Call parent method
parent::after();
}
}
Though the example is very simple it may be improved to what you want to archive. Basically I've finished up writing my own Controller_Template
to do the stuff I need. Also you may consider adding the format parameter to your urls so that the .html
urls returned the regular html representation of the data and .json
urls did the same, but in json format.
For more information (and probably ideas) see kerkness unofficial Kohana wiki
You don't really need a separate controller, you can use Kohana_Controller_Template for handling AJAX requests as well.
It's up to you to decide what will the response be in case of AJAX request (or subrequest, it's usually the same). I usually have the template actually rendered only in case of request being the initial one (and not-ajax), rendering it's $content var otherwise.
Also, you can easily check if a request is AJAX / subrequest:
if ($request->is_ajax())
if ( ! $request->is_initial())
Also, if using Kohana_Controller_Template as your controller parent/ancestor it is good to remember to disable auto-rendering when accessing via AJAX, to prevent loading and rendering whole template.
if ($request->is_ajax()) $this->auto_render = FALSE;
精彩评论