Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 handling sessions.

Thanks in advance

like image 525
Shameer Avatar asked Apr 06 '11 08:04

Shameer


2 Answers

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);
        }
like image 109
Enrique Avatar answered Oct 22 '22 14:10

Enrique


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

like image 38
Xobb Avatar answered Oct 22 '22 16:10

Xobb