simple PHP code sample to serve backbone.js

前端 未结 3 817
盖世英雄少女心
盖世英雄少女心 2021-02-02 16:33

Experience level: newbie.

The backbone.js Todos demo uses localStorage. This question is about how to use PHP to serve the page instead, assuming that a MySQL DB has bee

3条回答
  •  走了就别回头了
    2021-02-02 17:02

    The following should give you an idea (php controllers are implemented using Silex framework + Paris library for the data access):

    // GET  /{resource}/{id}    Show
    $app->get('/api/todos/{id}', function ($id) use ($app) {
        $todo =  $app['paris']->getModel('Todo')->find_one($id);
    
        return new Response(json_encode($todo->as_array()), 200, array('Content-Type' => 'application/json'));
    });
    
    // POST     /{resource}     Create
    $app->post('/api/todos', function (Request $request) use ($app) {
        $data = json_decode($request->getContent());
    
        $todo =  $app['paris']->getModel('Todo')->create();
        $todo->title = $data->title;
        $todo->save();
    
        return new Response(json_encode($todo->as_array()), 200, array('Content-Type' => 'application/json'));
    });
    
    // PUT  /{resource}/{id}    Update
    $app->put('/api/todos/{id}', function ($id, Request $request) use ($app) {
        $data = json_decode($request->getContent());
    
        $todo =  $app['paris']->getModel('Todo')->find_one($id);
        $todo->title = $data->title;
        $todo->save();
    
        return new Response('Todo updated', 200);
    });
    
    // DELETE   /{resource}/{id}    Destroy
    $app->delete('/api/todos/{id}', function ($id) use ($app) {
        $todo =  $app['paris']->getModel('Todo')->find_one($id);
        $todo->delete(); 
    
        return new Response('Todo deleted', 200);
    });
    

    To get your backbone collection working with the above interface, all you have to do is to set the url property like:

    window.TodoList = Backbone.Collection.extend({
        model: Todo,
    
        url: "api/todos",
    
        ...
    });
    

    Recently, I have written a tutorial on how to do GET/POST/PUT/DELETE with Backbone.js and PHP http://cambridgesoftware.co.uk/blog/item/59-backbonejs-%20-php-with-silex-microframework-%20-mysql, might be helpful.

提交回复
热议问题