# 創建REST服務
## 14.1 數據庫遷移
這個名字是源自于Ruby On Rails在那時候的印象,不直接使用MySQL的目的在于讓我們可以專注于過程。
### 14.1.1 創建表
表的概念,類似于在Excel中的表,如果你真實不懂數據庫。 讓我們創建一個athomes的表,為什么是athomes,因為以前在寫android程序的時候就叫的是athome,忽略掉這些次要的因素吧。
~~~
$ php artisan migrate:make create_athomes_table
~~~
打開 app/database/migrations/***create_athomes_table.php 這里的***是由日期和某些隨機變量組成的,修改生成的PHP代碼,如下:
~~~
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAthomesTable extends Migration {
public function up()
{
Schema::create('athomes', function(Blueprint $table)
{
$table--->increments('id');
$table->float('temperature');
$table->float('sensors1');
$table->float('sensors2');
$table->boolean('led1');
$table->timestamps();
});
}
public function down()
{
Schema::drop('athomes');
}
}
~~~
id值是自加的,也就是我們在localhost/athome/{id},當我們創建一個新的數據的時候,會自動加上去。最后一個timestamps批的是時間,會包含創建時間和修改時間。 剩下的temperature,sensors1,sensors2是小數,以及只有true和false的led1。
### 14.1.2 數據庫遷移
我們只是寫了我們需要的數據的格式而并沒有丟到數據庫里,
~~~
$ php artisan migrate
~~~
這個就是我們執行遷移的命令,如果你用phpmyadmin可以直接打開查看,沒有的話,可以。
~~~
$ mysql -uroot -p
~~~
~~~
use iot;
select * from athomes;
~~~
就可以看到我們寫的東西,那么接下來就是創建RESTful服務了
## 14.2 創建RESTful
用下面的代碼實現我們稱之為Athomes控制器的創建
~~~
$ php artisan controller:make AthomesController
~~~
就會在app/controllers下面生成下面的代碼
~~~
class AthomesController extends \BaseController {
public function index() {}
public function create() {}
public function store() {}
public function show($id) {}
public function edit($id) {}
public function update($id) {}
public function destroy($id) {}
}
~~~
## 14.3 Laravel Resources
上面的代碼過于沉重,請讓我用 Ctrl+C 來帶來點知識吧。
|
Verb
|
Path
|
Action
|
Route Name
|
| --- | --- | --- | --- |
|
GET
|
/resource
|
index
|
resource.index
|
|
GET
|
/resource/create
|
create
|
resource.create
|
|
POST
|
/resource
|
store
|
resource.store
|
|
GET
|
/resource/{resource}
|
show
|
resource.show
|
|
GET
|
/resource/{resource}/edit
|
edit
|
resource.edit
|
|
PUT/PATCH
|
/resource/{resource}
|
update
|
resource.update
|
|
DELETE
|
/resource/{resource}
|
destroy
|
resource.destroy
|
所以我們只需要專注于創建 create, edit, show, destory 等等。好吧,你可能沒有耐心了,但是在修改這個之前我們需要先在 app/model 加個 class
~~~
class Athomes extends Eloquent {
protected $table = 'athomes';
}
~~~
如果你想要的只是控制器Athomes的代碼的話。。
~~~
class AthomesController extends \BaseController {
public $restful=true;
protected $athome;
public function __construct(Athomes $athome)
{
$this--->athome = $athome ;
}
public function index()
{
$maxid=Athomes::all();
return Response::json($maxid);
}
public function create()
{
$maxid=Athomes::max('id');
return View::make('athome.create')->with('maxid',$maxid);
}
public function store()
{
$rules = array(
'led1'=>'required',
'sensors1' => 'required|numeric|Min:-50|Max:80',
'sensors2' => 'required|numeric|Min:-50|Max:80',
'temperature' => 'required|numeric|Min:-50|Max:80'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('athome/create')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$nerd = new Athomes;
$nerd->sensors1 = Input::get('sensors1');
$nerd->sensors2 = Input::get('sensors2');
$nerd->temperature = Input::get('temperature');
$nerd->led1 = Input::get('led1');
$nerd->save();
Session::flash('message', 'Successfully created athome!');
return Redirect::to('athome');
}
}
public function show($id)
{
$myid=Athomes::find($id);
$maxid=Athomes::where('id','=',$id)
->select('id','temperature','sensors1','sensors2','led1')
->get();
return Response::json($maxid);
}
public function edit($id)
{
$athome = Athomes::find($id);
return View::make('athome.edit')
->with('athome', $athome);
}
public function update($id)
{
$rules = array(
'led1'=>'required|',
'sensors1' => 'required|numeric|Min:-50|Max:80',
'sensors2' => 'required|numeric|Min:-50|Max:80',
'temperature' => 'required|numeric|Min:-50|Max:80'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('athome/' . $id . '/edit')
->withErrors($validator);
} else {
$nerd = Athomes::find($id);
$nerd->sensors1 = Input::get('sensors1');
$nerd->sensors2 = Input::get('sensors2');
$nerd->temperature = Input::get('temperature');
$nerd->led1 = Input::get('led1');
$nerd->save();
Session::flash('message', 'Successfully created athome!');
return Redirect::to('athome');
}
}
public function destroy($id)
{
$athome = Athomes::find($id);
$athome->delete();
if(is_null($athome))
{
return Response::json('Todo not found', 404);
}
Session::flash('message', 'Successfully deleted the nerd!');
return Redirect::to('athome');
}
}
~~~
希望你能讀懂,沒有的話,繼續。
下面這部分來自于之前的博客,這里就不多加論述了。 這個也就是我們要的模板,
### 14.3.1 修改Create()
~~~
public function create()
{
$maxid=Athomes::max('id');
return View::make('athome.create')->with('maxid',$maxid);
}
~~~
這里需要在app/views/創建一個athome里面創建一個create.blade.php,至于maxid,暫時還不需要,后面會用到show。如果只需要模板,可以簡化為
~~~
public function create()
{
return View::make('athome.create');
}
~~~
這里只是對其中代碼的進行一下說明。
### 14.3.2 創建前臺頁面
#### 14.3.2.1 開始之前
由于使用到了bootstrap以及bootstrap-select,記得添加css。
~~~
<link rel="stylesheet" type="text/css" href="<?= url('css/bootstrap.min.css') ?>" />
<link rel="stylesheet" type="text/css" href="<?= url('css/bootstrap-select.min.css') ?>" />
~~~
以及javascript
~~~
<script type="text/javascript" src="<?= url('js/jquery.min.js')?>"></script>
<script type="text/javascript" src="<?= url('js/bootstrap.min.js') ?>"></script>
<script type="text/javascript" src="<?= url('js/bootstrap-select.min.js') ?>"></script>
<script>
$('.selectpicker').selectpicker();
</script>
~~~
#### 14.3.2.2 創建資源頁面
這里用到的是之前提到的那個作者寫下的,稍微修改了一下。
~~~
<div class="row-fluid">
{{ HTML::ul($errors->all()) }}
{{ Form::open(array('url' => 'athome')) }}
<div class="form-group">
{{ Form::label('led1', '開關1') }}
{{ Form::select('led1',array('關','開'),$selected=NULL,array('class'=>'selectpicker')) }}
</div>
<div class="form-group">
{{ Form::label('sensors1', 'sensors1') }}
{{ Form::text('sensors1', Input::old('sensors1'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('sensors2', 'sensors2') }}
{{ Form::text('sensors2', Input::old('sensors2'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('temperature', 'temperature') }}
{{ Form::text('temperature', Input::old('temperature'), array('class' => 'form-control')) }}
</div>
{{ Form::submit('Create!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
</div>
~~~
開關一開始打算用 checkbox,加上 bootstrap-switch 實現
~~~
ON OFF
~~~
弱弱地覺得還是沒掌握好的節奏,所以最后用 select 來實現。
還需要修改一下之前的 create(),添加一行
~~~
return Redirect::to('athome');
~~~
也就是添加完后,重定向到首頁查看,最后例子給出的 create 如下
~~~
public function store()
{
$rules = array(
'led1'=>'required',
'sensors1' => 'required|numeric|Min:-50|Max:80',
'sensors2' => 'required|numeric|Min:-50|Max:80',
'temperature' => 'required|numeric|Min:-50|Max:80'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('athome/create')
->withErrors($validator);
} else {
// store
$nerd = new Athomes;
$nerd->sensors1 = Input::get('sensors1');
$nerd->sensors2 = Input::get('sensors2');
$nerd->temperature = Input::get('temperature');
$nerd->led1 = Input::get('led1');
$nerd->save();
Session::flash('message', 'Successfully created athome!');
return Redirect::to('athome');
}
}
~~~
效果圖:

### 14.3.4 更新資源頁面
完整的 blade 模板文件
~~~
<!DOCTYPE html lang="zh-cn">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width">
<meta name="description" content="">
<title>@yield('title')</title>
<link rel="stylesheet" type="text/css" href="<?= url('css/bootstrap.min.css') ?>" />
<link rel="stylesheet" type="text/css" href="<?= url('css/bootstrap-select.min.css') ?>" />
<link rel="stylesheet" href="<?= url('css/justified-nav.css') ?>" type="text/css" media="screen" />
</head>
<body>
<div class="container">
<div class="container">
<div class="row-fluid">
<h1>Edit {{ $athome->id }}</h1>
<!-- if there are creation errors, they will show here -->
{{ HTML::ul($errors->all()) }}
{{ Form::model($athome, array('route' => array('athome.update', $athome->id), 'method' => 'PUT')) }}
<div class="form-group">
{{ Form::label('led1', '開關1') }}
{{ Form::select('led1',array('關','開'),$selected=NULL,array('class'=>'selectpicker')) }}
</div>
<div class="form-group">
{{ Form::label('sensors1', '傳感器1') }}
{{ Form::text('sensors1', Input::old('sensors1'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('sensors2', '傳感器2') }}
{{ Form::text('sensors2', Input::old('sensors2'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('temperature', '溫度傳感器') }}
{{ Form::text('temperature', Input::old('temperature'), array('class' => 'form-control')) }}
</div>
{{ Form::submit('Edit the Nerd!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
</div>
</div>
<div class="footer">
<p>? Company 2013</p>
</div>
</div>
</div>
<script type="text/javascript" src="<?= url('js/jquery.min.js')?>"></script>
<script type="text/javascript" src="<?= url('js/bootstrap.min.js') ?>"></script>
<script type="text/javascript" src="<?= url('js/bootstrap-select.min.js') ?>"></script>
<script>
$('.selectpicker').selectpicker();
</script>
<script type="text/javascript" src="<?= url('js/log.js') ?>"></script>
</body>
</html>
~~~
效果圖:

最后效果見:[http://b.phodal.com/](http://b.phodal.com/)
* [**一步步搭建物聯網系統**](http://www.ituring.com.cn/book/1580)
* [前言](http://www.ituring.com.cn/tupubarticle/3778)
* [第一部分](http://www.ituring.com.cn/tupubarticle/3801)
* [1 無處不在的HTML](http://www.ituring.com.cn/tupubarticle/3779)
* [2 無處不在的Javascript](http://www.ituring.com.cn/tupubarticle/3780)
* [3 無處不在的CSS](http://www.ituring.com.cn/tupubarticle/3781)
* [4 無處不在的三劍客](http://www.ituring.com.cn/tupubarticle/3782)
* [5 GNU/Linux 強大且Free](http://www.ituring.com.cn/tupubarticle/3783)
* [6 Arduino 極客的玩具](http://www.ituring.com.cn/tupubarticle/3784)
* [7 Python 代碼如散文](http://www.ituring.com.cn/tupubarticle/3785)
* [8 Raspberry Pi 極客的盛宴](http://www.ituring.com.cn/tupubarticle/3786)
* [9 Server 一切皆為服務](http://www.ituring.com.cn/tupubarticle/3787)
* [10 Web服務](http://www.ituring.com.cn/tupubarticle/3788)
* [11 HTTP 熟悉&陌生](http://www.ituring.com.cn/tupubarticle/3789)
* [12 設計RESTful API](http://www.ituring.com.cn/tupubarticle/3790)
* [第二部分](http://www.ituring.com.cn/tupubarticle/3802)
* [13 環境準備](http://www.ituring.com.cn/tupubarticle/3791)
* [?14 創建REST服務](http://www.ituring.com.cn/tupubarticle/3792)
* [15 REST與不同語言](http://www.ituring.com.cn/tupubarticle/3793)
* [16 前端顯示](http://www.ituring.com.cn/tupubarticle/3794)
* [17 RESTful的CoAP協議](http://www.ituring.com.cn/tupubarticle/3795)
* [第三部分](http://www.ituring.com.cn/tupubarticle/3803)
* [18 簡單物聯網](http://www.ituring.com.cn/tupubarticle/3797)
* [19 Android簡單示例](http://www.ituring.com.cn/tupubarticle/3798)
* [尾聲](http://www.ituring.com.cn/tupubarticle/3799)