文档章节

Create a restful application with AngularJS and CakePHP (II)

hantsy
 hantsy
发布于 2013/11/10 13:50
字数 923
阅读 108
收藏 1

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

© 著作权归作者所有

共有 人打赏支持
hantsy
粉丝 113
博文 88
码字总数 78079
作品 0
浦东
程序员
私信 提问
Migrating a SpringWebMVC App from JSP to AngularJS

Migrating a Spring Web MVC application from JSP to AngularJS Engineering Michael Isvy August 19, 2015 Note on authors This post is a guest post by Han Lim and Tony Nguyen.Han an......

miscellanea
2015/08/24
0
0
开源中国的 AngularJS 优秀文章汇总

Angular JS (Angular.JS) 是一组用来开发Web页面的框架、模板以及数据绑定和丰富UI组件。它支持整个开发进程,提供web应用的架构,无需进行手工DOM操作。 AngularJS很小,只有60K,兼容主流浏...

oschina
2014/08/24
5.7K
13
AngularJS - Top 6 Concepts that Developers Loved

This article represents top 6 popular AngularJS topics that has been used most by the AngularJS developer community to date. The inference is derived based on number of tagged d......

perfectspr
2014/12/03
0
0
Angular model objects with JavaScript classes

Angular model objects with JavaScript classes The missing piece in AngularJS Unlike Backbone and Ember, AngularJS does not provide a standardized way to define model objects. Th......

Finley.Hamilton
2014/10/13
0
0
OSChina 技术专题之 AngularJS 更新版(201412)

Angular JS (Angular.JS) 是一组用来开发Web页面的框架、模板以及数据绑定和丰富UI组件。它支持整个开发进程,提供web应用的架构,无需进行手工DOM操作。 AngularJS很小,只有60K,兼容主流浏...

OSC编辑部
2014/10/17
11.1K
26

没有更多内容

加载失败,请刷新页面

加载更多

java框架学习日志-13(Mybatis基本概念和简单的例子)

在mybatis初次学习Mybatis的时候,遇到了很多问题,虽然阿里云的视频有教学,但是视频教学所使用的软件和我自己使用的软件不用,我自己用的数据库是oracle数据库,开发环境是idea。而且视频中...

白话
今天
3
0
Java基础:String、StringBuffer和StringBuilder的区别

1 String String:字符串常量,字符串长度不可变。Java中String是immutable(不可变)的。 String类的包含如下定义: /** The value is used for character storage. */private final cha...

watermelon11
今天
2
0
mogodb服务

部署MongoDB 官网: https://www.mongodb.com/download-center/community 创建mongo数据目录 mkdir /data/mongodb 二进制部署 wget -c https://fastdl.mongodb.org/linux/mongodb-linux-x8......

以谁为师
昨天
5
0
大神教你Debian GNU/Linux 9.7 “Stretch” Live和安装镜像开放下载

Debian项目团队于昨天发布了Debian GNU/Linux 9 "Stretch" 的第7个维护版本更新,重点修复了APT软件管理器中存在的安全漏洞。在敦促每位用户尽快升级系统的同时,Debian团队还发布了Debian ...

linux-tao
昨天
4
0
PHP 相关配置

1. php-fpm的pool 编辑php-fpm配置文件php-fpm.con vim /usr/local/php/etc/php-fpm.conf //在[global]部分增加以下内容 include = etc/php-fpm.d/*.conf # 相当与Nginx的虚拟主机文件 “vho......

Yue_Chen
昨天
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部