Jon Stuebe

Backbone.js & FuelPHP

backbone.js fuelphp

Backbone.js & FuelPHP

Posted by Jon Stuebe on .
Featured

backbone.js fuelphp

Backbone.js & FuelPHP

Posted by Jon Stuebe on .

Recently I’ve started working with Backbone.js and started to integrate it into FuelPHP, my current framework of choice. Backbone’s sync feature uses a restful set of ajax requests to hook up the javascript mvc to the backend of your choice. In the case of FuelPHP, I had some issues since Fuel’s Validation class uses the POST variables by default, and Backbone sends over all of the variables in a JSON string. To combat this, I’m using the Hybrid Controller with no custom routes. Pretty awesome really. Here’s the start of the controller:

{% highlight php linenos %} class ControllerTodos extends ControllerHybrid
{

public function action_index()
{
    $data['todos'] = Model_Todo::find('all');
    $this->template->title = "Todos";
    $this->template->content = View::forge('todos/index', $data); 
}

public function get_index()
{
    if(Input::get('id'))
    {
        $id = Input::get('id');
        $todo = Model_Todo::find($id);
        $this->response($todo);
    }
    else
    {
        $todos = Model_Todo::find('all');
        $this->response($todos);
    }
}

public function post_index()
{
    $val = Model_Todo::validate('create');

    if ($val->run(Input::json()))
    {
        $todo = Model_Todo::forge(array(
            'title' => Input::json('title'),
            'description' => Input::json('description'),
            'completed' => Input::json('completed'),
        ));

        if ($todo and $todo->save())
        {
            $this->response($todo);
        }

        else
        {
            $this->response(array(
                'error' => true,
            ));
        }
    }
}{% endhighlight %}
user

Jon Stuebe