创建REST服务

数据库迁移

这个名字是源自于Ruby On Rails在那时候的印象,不直接使用MySQL的目的在于让我们可以专注于过程。

创建表

表的概念,类似于在Excel中的表,如果你真实不懂数据库。 让我们创建一个athomes的表,为什么是athomes,因为以前在写android程序的时候就叫的是athome,忽略掉这些次要的因素吧。

  1. $ php artisan migrate:make create_athomes_table

打开 app/database/migrations/create_athomes_table.php这里的是由日期和某些东西组成的,修改生成的代码为下面。

  1. use Illuminate\Database\Schema\Blueprint;
  2. use Illuminate\Database\Migrations\Migration;
  3. class CreateAthomesTable extends Migration {
  4. public function up()
  5. {
  6. Schema::create('athomes', function(Blueprint $table)
  7. {
  8. $table--->increments('id');
  9. $table->float('temperature');
  10. $table->float('sensors1');
  11. $table->float('sensors2');
  12. $table->boolean('led1');
  13. $table->timestamps();
  14. });
  15. }
  16. public function down()
  17. {
  18. Schema::drop('athomes');
  19. }
  20. }

意思大致就是id是自加的,也就是我们在localhost/athome/{id},当我们创建一个新的数据的时候,会自动加上去,最后一个timestamps批的是时间,会包含创建时间和修改时间。 剩下的temperature,sensors1,sensors2是小数,以及只有真和假的led1。

数据库迁移

我们只是写了我们需要的数据的格式而并没有丢到数据库里,

  1. $ php artisan migrate

这个就是我们执行迁移的命令,如果你用phpmyadmin可以直接打开查看,没有的话,可以。

  1. $ mysql -uroot -p
  1. use iot;
  2. select * from athomes;

就可以看到我们写的东西,那么接下来就是创建RESTful服务了

创建RESTful

用下面的代码实现我们称之为Athomes控制器的创建

  1. $ php artisan controller:make AthomesController

就会在app/controllers下面生成下面的代码

  1. class AthomesController extends \BaseController {
  2. public function index() {}
  3. public function create() {}
  4. public function store() {}
  5. public function show($id) {}
  6. public function edit($id) {}
  7. public function update($id) {}
  8. public function destroy($id) {}
  9. }

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

  1. class Athomes extends Eloquent {
  2. protected $table = 'athomes';
  3. }

如果你想要的只是控制器Athomes的代码的话。。

  1. class AthomesController extends \BaseController {
  2. public $restful=true;
  3. protected $athome;
  4. public function __construct(Athomes $athome)
  5. {
  6. $this--->athome = $athome ;
  7. }
  8. public function index()
  9. {
  10. $maxid=Athomes::all();
  11. return Response::json($maxid);
  12. }
  13. public function create()
  14. {
  15. $maxid=Athomes::max('id');
  16. return View::make('athome.create')->with('maxid',$maxid);
  17. }
  18. public function store()
  19. {
  20. $rules = array(
  21. 'led1'=>'required',
  22. 'sensors1' => 'required|numeric|Min:-50|Max:80',
  23. 'sensors2' => 'required|numeric|Min:-50|Max:80',
  24. 'temperature' => 'required|numeric|Min:-50|Max:80'
  25. );
  26. $validator = Validator::make(Input::all(), $rules);
  27. if ($validator->fails()) {
  28. return Redirect::to('athome/create')
  29. ->withErrors($validator)
  30. ->withInput(Input::except('password'));
  31. } else {
  32. $nerd = new Athomes;
  33. $nerd->sensors1 = Input::get('sensors1');
  34. $nerd->sensors2 = Input::get('sensors2');
  35. $nerd->temperature = Input::get('temperature');
  36. $nerd->led1 = Input::get('led1');
  37. $nerd->save();
  38. Session::flash('message', 'Successfully created athome!');
  39. return Redirect::to('athome');
  40. }
  41. }
  42. public function show($id)
  43. {
  44. $myid=Athomes::find($id);
  45. $maxid=Athomes::where('id','=',$id)
  46. ->select('id','temperature','sensors1','sensors2','led1')
  47. ->get();
  48. return Response::json($maxid);
  49. }
  50. public function edit($id)
  51. {
  52. $athome = Athomes::find($id);
  53. return View::make('athome.edit')
  54. ->with('athome', $athome);
  55. }
  56. public function update($id)
  57. {
  58. $rules = array(
  59. 'led1'=>'required|',
  60. 'sensors1' => 'required|numeric|Min:-50|Max:80',
  61. 'sensors2' => 'required|numeric|Min:-50|Max:80',
  62. 'temperature' => 'required|numeric|Min:-50|Max:80'
  63. );
  64. $validator = Validator::make(Input::all(), $rules);
  65. if ($validator->fails()) {
  66. return Redirect::to('athome/' . $id . '/edit')
  67. ->withErrors($validator);
  68. } else {
  69. $nerd = Athomes::find($id);
  70. $nerd->sensors1 = Input::get('sensors1');
  71. $nerd->sensors2 = Input::get('sensors2');
  72. $nerd->temperature = Input::get('temperature');
  73. $nerd->led1 = Input::get('led1');
  74. $nerd->save();
  75. Session::flash('message', 'Successfully created athome!');
  76. return Redirect::to('athome');
  77. }
  78. }
  79. public function destroy($id)
  80. {
  81. $athome = Athomes::find($id);
  82. $athome->delete();
  83. if(is_null($athome))
  84. {
  85. return Response::json('Todo not found', 404);
  86. }
  87. Session::flash('message', 'Successfully deleted the nerd!');
  88. return Redirect::to('athome');
  89. }
  90. }

希望你能读懂,没有的话,继续。

下面这部分来自于之前的博客,这里就不多加论述了。 这个也就是我们要的模板,

修改Create()

  1. public function create()
  2. {
  3. $maxid=Athomes::max('id');
  4. return View::make('athome.create')->with('maxid',$maxid);
  5. }

这里需要在app/views/创建一个athome里面创建一个create.blade.php,至于maxid,暂时还不需要,后面会用到show。如果只需要模板,可以简化为

  1. public function create()
  2. {
  3. return View::make('athome.create');
  4. }

这里只是对其中代码的进行一下说明。

创建表单

创建表单之前

由于使用到了bootstrap以及bootstrap-select,记得添加css。

  1. <link rel="stylesheet" type="text/css" href="<?= url('css/bootstrap.min.css') ?>" />
  2. <link rel="stylesheet" type="text/css" href="<?= url('css/bootstrap-select.min.css') ?>" />

以及javascript

  1. <script type="text/javascript" src="<?= url('js/jquery.min.js')?>"></script>
  2. <script type="text/javascript" src="<?= url('js/bootstrap.min.js') ?>"></script>
  3. <script type="text/javascript" src="<?= url('js/bootstrap-select.min.js') ?>"></script>
  4. <script>
  5. $('.selectpicker').selectpicker();
  6. </script>

创建表单

这里用到的是之前提到的那个作者写下的,稍微修改了一下。

  1. <div class="row-fluid">
  2. {{ HTML::ul($errors->all()) }}
  3. {{ Form::open(array('url' => 'athome')) }}
  4. <div class="form-group">
  5. {{ Form::label('led1', '开关1') }}
  6. {{ Form::select('led1',array('关','开'),$selected=NULL,array('class'=>'selectpicker')) }}
  7. </div>
  8. <div class="form-group">
  9. {{ Form::label('sensors1', 'sensors1') }}
  10. {{ Form::text('sensors1', Input::old('sensors1'), array('class' => 'form-control')) }}
  11. </div>
  12. <div class="form-group">
  13. {{ Form::label('sensors2', 'sensors2') }}
  14. {{ Form::text('sensors2', Input::old('sensors2'), array('class' => 'form-control')) }}
  15. </div>
  16. <div class="form-group">
  17. {{ Form::label('temperature', 'temperature') }}
  18. {{ Form::text('temperature', Input::old('temperature'), array('class' => 'form-control')) }}
  19. </div>
  20. {{ Form::submit('Create!', array('class' => 'btn btn-primary')) }}
  21. {{ Form::close() }}
  22. </div>

开关一开始打算用 checkbox,加上 bootstrap-switch 实现 ON OFF 弱弱地觉得还是没掌握好的节奏,所以最后用 select 来实现。

还需要修改一下之前的 create(),添加一行

  1. return Redirect::to('athome');

也就是添加完后,重定向到首页查看,最后例子给出的 create 如下

  1. public function store()
  2. {
  3. $rules = array(
  4. 'led1'=>'required',
  5. 'sensors1' => 'required|numeric|Min:-50|Max:80',
  6. 'sensors2' => 'required|numeric|Min:-50|Max:80',
  7. 'temperature' => 'required|numeric|Min:-50|Max:80'
  8. );
  9. $validator = Validator::make(Input::all(), $rules);
  10. if ($validator->fails()) {
  11. return Redirect::to('athome/create')
  12. ->withErrors($validator);
  13. } else {
  14. // store
  15. $nerd = new Athomes;
  16. $nerd->sensors1 = Input::get('sensors1');
  17. $nerd->sensors2 = Input::get('sensors2');
  18. $nerd->temperature = Input::get('temperature');
  19. $nerd->led1 = Input::get('led1');
  20. $nerd->save();
  21. Session::flash('message', 'Successfully created athome!');
  22. return Redirect::to('athome');
  23. }
  24. }

编辑模板

完整的 blade 模板文件

  1. <!DOCTYPE html lang="zh-cn">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  5. <meta name="keywords" content="">
  6. <meta name="viewport" content="width=device-width">
  7. <meta name="description" content="">
  8. <title>@yield('title')</title>
  9. <link rel="stylesheet" type="text/css" href="<?= url('css/bootstrap.min.css') ?>" />
  10. <link rel="stylesheet" type="text/css" href="<?= url('css/bootstrap-select.min.css') ?>" />
  11. <link rel="stylesheet" href="<?= url('css/justified-nav.css') ?>" type="text/css" media="screen" />
  12. </head>
  13. <body>
  14. <div class="container">
  15. <div class="container">
  16. <div class="row-fluid">
  17. <h1>Edit {{ $athome->id }}</h1>
  18. <!-- if there are creation errors, they will show here -->
  19. {{ HTML::ul($errors->all()) }}
  20. {{ Form::model($athome, array('route' => array('athome.update', $athome->id), 'method' => 'PUT')) }}
  21. <div class="form-group">
  22. {{ Form::label('led1', '开关1') }}
  23. {{ Form::select('led1',array('关','开'),$selected=NULL,array('class'=>'selectpicker')) }}
  24. </div>
  25. <div class="form-group">
  26. {{ Form::label('sensors1', '传感器1') }}
  27. {{ Form::text('sensors1', Input::old('sensors1'), array('class' => 'form-control')) }}
  28. </div>
  29. <div class="form-group">
  30. {{ Form::label('sensors2', '传感器2') }}
  31. {{ Form::text('sensors2', Input::old('sensors2'), array('class' => 'form-control')) }}
  32. </div>
  33. <div class="form-group">
  34. {{ Form::label('temperature', '温度传感器') }}
  35. {{ Form::text('temperature', Input::old('temperature'), array('class' => 'form-control')) }}
  36. </div>
  37. {{ Form::submit('Edit the Nerd!', array('class' => 'btn btn-primary')) }}
  38. {{ Form::close() }}
  39. </div>
  40. </div>
  41. <div class="footer">
  42. <p>© Company 2013</p>
  43. </div>
  44. </div>
  45. </div>
  46. <script type="text/javascript" src="<?= url('js/jquery.min.js')?>"></script>
  47. <script type="text/javascript" src="<?= url('js/bootstrap.min.js') ?>"></script>
  48. <script type="text/javascript" src="<?= url('js/bootstrap-select.min.js') ?>"></script>
  49. <script>
  50. $('.selectpicker').selectpicker();
  51. </script>
  52. <script type="text/javascript" src="<?= url('js/log.js') ?>"></script>
  53. </body>
  54. </html>

效果图:

Blade Edit

最后效果见:http://b.phodal.com/