Create a restful application with AngularJS and CakePHP (II)

#Create a restful application with AngularJS and CakePHP (II)

#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.

<pre> /* 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()); </pre>

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.

<pre> Vendor\pear-pear.cakephp.org\CakePHP\bin\cake.bat bake model Post </pre>

This command will generate a Model named Post, it is under Model folder.

<pre> class Post extends AppModel { } </pre>

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.

<pre> Vendor\pear-pear.cakephp.org\CakePHP\bin\cake.bat bake controller posts </pre>

After it is executed and a file named PostsController.php will be generated in the Controller folder.

<pre> class PostsController extends AppController { public $scaffold; } </pre>

A controller class must extends AppController, it is similar with the AppModel. It is a place holder to customize the common controller lifecycle. All controllers in this application should extend AppController

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,

<pre> Vendor\pear-pear.cakephp.org\CakePHP\bin\cake.bat bake controller </pre>

The bake command will guide you to generate the PostsController step 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 model Post.

<pre> 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') )); } </pre>

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.

<pre> public $components = array('RequestHandler'); </pre>

Open Config/routes.php, add the following lines before require CAKE . 'Config' . DS . 'routes.php';.

<pre> Router::mapResources("posts"); Router::parseExtensions(); </pre>

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.

<pre> { "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 } } ] } </pre>

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.

<table> <thead> <tr><td>URL</td><td>HTTP Method</td><td>PostsController method</td><td>Description</td></tr> </thead> <tbody> <tr><td>/posts.json</td><td>GET</td><td>index</td><td>Get the list of Posts</td></tr> <tr><td>/posts.json</td><td>POST</td><td>add</td><td>Create a new Post</td></tr> <tr><td>/posts/:id.json</td><td>GET</td><td>view</td><td>Get the details of a Post</td></tr> <tr><td>/posts/:id.json</td><td>PUT</td><td>edit</td><td>Update a Post by id</td></tr> <tr><td>/posts/:id.json</td><td>DELETE</td><td>delete</td><td>Delete a Post by id</td></tr> </tbody> </table>

If you want to change the resource mapping, you can define your rules via Router::resourceMap in Config/routes.php.

<pre> 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) )); </pre>

Alternatively, you can use Router::connect to define the route rule directly.

##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.

转载于:https://my.oschina.net/hantsy/blog/175265

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值