跳至主要内容

Create a restful application with AngularJS and CakePHP(II): Bake backend REST API


Bake backend REST API

I will reuse the database scheme of the CakePHP Blog tutorial.

Prepare posts table

Execute the following scripts to create a posts table in your MySQL database, it also initialized the sample data.
/* First, create our posts table: */
CREATE TABLE posts (
 id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 title VARCHAR(50),
 body TEXT,
 created DATETIME DEFAULT NULL,
 modified DATETIME DEFAULT NULL
);

/* Then insert some posts for testing: */
INSERT INTO posts (title,body,created)
VALUES (’The title’, ’This is the post body.’, NOW());
INSERT INTO posts (title,body,created)
VALUES (’A title once again’, ’And the post body follows.’, NOW());
INSERT INTO posts (title,body,created)
VALUES (’Title strikes back’, ’This is really exciting! Not.’, NOW());
You can use MySQL client command line or MySQL Workbench(GUI) to complete this work.

Bake the skeleton of model and controller

Use bake command line to generate model, controller for posts table.
 Vendor\pear-pear.cakephp.org\CakePHP\bin\cake.bat bake model Post
This command will generate a Model named Post, it is under Modelfolder.
class Post extends AppModel {

}
A model class must extend AppModel which is a base class in the same folder, it is a place holder to customize common model hooks for all models in your application.
Use the following command to generate the posts controller.
 Vendor\pear-pear.cakephp.org\CakePHP\bin\cake.bat bake controller posts
After it is executed and a file named PostsController.php will be generated in the Controller folder.
class PostsController extends AppController {
 public $scaffold;
}
A controller class must extends AppController, it is similar with theAppModel. It is a place holder to customize the common controller lifecycle. All controllers in this application should extendAppController
The naming of table, model and controller follows the CakePHP naming convention.
You can also use cake bake all to generate model, controller and view together. Of course, I do not need the view in this project, as described formerly, we will use AngularJS to build the frontend UI.
If you want to generate the codes interactively, ignore the name argument in the bake command line.
For example,
 Vendor\pear-pear.cakephp.org\CakePHP\bin\cake.bat bake controller 
The bake command will guide you to generate the PostsControllerstep by step, you can also generate the CRUD dummy codes instead of the default public $scaffold;.
But the generated CRUD methods are ready for web pages, we will replace them with REST resource operations.

Make the controller restful

Open PostsController and add the basic CRUD methods for modelPost.
public function index() {
        $posts = $this->Post->find('all');
        $this->set(array(
            'posts' => $posts,
            '_serialize' => array('posts')
        ));
    }

    public function view($id) {
        $post = $this->Post->findById($id);
        $this->set(array(
            'post' => $post,
            '_serialize' => array('post')
        ));
    }

    public function add() {
        //$this->Post->id = $id;
        if ($this->Post->save($this->request->data)) {
            $message = array(
                'text' => __('Saved'),
                'type' => 'success'
            );
        } else {
            $message = array(
                'text' => __('Error'),
                'type' => 'error'
            );
        }
        $this->set(array(
            'message' => $message,
            '_serialize' => array('message')
        ));
    }

    public function edit($id) {
        $this->Post->id = $id;
        if ($this->Post->save($this->request->data)) {
            $message = array(
                'text' => __('Saved'),
                'type' => 'success'
            );
        } else {
            $message = array(
                'text' => __('Error'),
                'type' => 'error'
            );
        }
        $this->set(array(
            'message' => $message,
            '_serialize' => array('message')
        ));
    }

    public function delete($id) {
        if ($this->Post->delete($id)) {
            $message = array(
                'text' => __('Deleted'),
                'type' => 'success'
            );
        } else {
            $message = array(
                'text' => __('Error'),
                'type' => 'error'
            );
        }
        $this->set(array(
            'message' => $message,
            '_serialize' => array('message')
        ));
    }
As you see, we must use _serialize as the key of the associated array of the returned result.
Besides these, RequestHandler component is required to process the REST resource request.
public $components = array('RequestHandler');
Open Config/routes.php, add the following lines beforerequire CAKE . 'Config' . DS . 'routes.php';.
Router::mapResources("posts");
Router::parseExtensions();
Router::mapResources indicates which posts will be mapped as REST resources, and Router::parseExtensions will parse the resources according to the file extension, XML and JSON are native supported.
Now navigate to http://localhost/posts.json, you will get the following JSON string in browser.
{
    "posts": [
        {
            "Post": {
                "id": "1",
                "title": "The title",
                "body": "This is the post body.",
                "created": "2013-10-22 16:10:53",
                "modified": null
            }
        },
        {
            "Post": {
                "id": "2",
                "title": "A title once again",
                "body": "And the post body follows.",
                "created": "2013-10-22 16:10:53",
                "modified": null
            }
        },
        {
            "Post": {
                "id": "3",
                "title": "Title strikes back",
                "body": "This is really exciting! Not.",
                "created": "2013-10-22 16:10:53",
                "modified": null
            }
        }
    ]
}
When access http://localhost/posts.json, it will call the index method of PostsController, and render the data as JOSN format. CakePHP follows the following rules to map REST resources to controllers. Here I use PostsController as an example to describe it.
URLHTTP MethodPostsController methodDescription
/posts.jsonGETindexGet the list of Posts
/posts.jsonPOSTaddCreate a new Post
/posts/:id.jsonGETviewGet the details of a Post
/posts/:id.jsonPUTeditUpdate a Post by id
/posts/:id.jsonDELETEdeleteDelete a Post by id
If you want to change the resource mapping, you can define your rules via Router::resourceMap in Config/routes.php.
Router::resourceMap(array(
 array(’action’ => ’index’, ’method’ => ’GET’, ’id’ => false),
 array(’action’ => ’view’, ’method’ => ’GET’, ’id’ => true),
 array(’action’ => ’add’, ’method’ => ’POST’, ’id’ => false),
 array(’action’ => ’edit’, ’method’ => ’PUT’, ’id’ => true),
 array(’action’ => ’delete’, ’method’ => ’DELETE’, ’id’ => true),
 array(’action’ => ’update’, ’method’ => ’POST’, ’id’ => true)
));
Alternatively, you can use Router::connect to define the route rule manually.

Summary

CakePHP REST API producing is simple and stupid, the only thing make me a little incompatible is the produced JSON data, the JSON data structure is a little tedious.

评论

此博客中的热门博文

AngularJS CakePHP Sample codes

Introduction This sample is a Blog application which has the same features with the official CakePHP Blog tutorial, the difference is AngularJS was used as frontend solution, and CakePHP was only use for building backend RESR API. Technologies AngularJS   is a popular JS framework in these days, brought by Google. In this example application, AngularJS and Bootstrap are used to implement the frontend pages. CakePHP   is one of the most popular PHP frameworks in the world. CakePHP is used as the backend REST API producer. MySQL   is used as the database in this sample application. A PHP runtime environment is also required, I was using   WAMP   under Windows system. Post links I assume you have some experience of PHP and CakePHP before, and know well about Apache server. Else you could read the official PHP introduction( php.net ) and browse the official CakePHP Blog tutorial to have basic knowledge about CakePHP. In these posts, I tried to follow the steps describ

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa