(三)——?jiǎng)?chuàng)建RESTful

2018-02-24 15:43 更新

原文出處:https://www.phodal.com/blog/bare-minimum-iot-system-create-restful/

數(shù)據(jù)庫(kù)的目的在于存儲(chǔ)數(shù)據(jù)等等的閑話這里就不多說(shuō)了,創(chuàng)建一個(gè)RESTful的目的在于產(chǎn)生下面的JSON格式數(shù)據(jù),以便于我們?cè)贏ndroid、Java、Python、jQuery等語(yǔ)言框架或者平臺(tái)上可以調(diào)用,最主要的是可以直接用Ajax來(lái)產(chǎn)生更炫目的效果。

    {
    id: 1,
    temperature: 14,
    sensors1: 12,
    sensors2: 12,
    led1: 0
    }

數(shù)據(jù)庫(kù)遷移

這個(gè)名字是源自于Ruby On Rails在那時(shí)候的印象,不直接使用MySQL的目的在于讓我們可以專注于過(guò)程。

創(chuàng)建表

表的概念,類似于在Excel中的表,如果你真實(shí)不懂?dāng)?shù)據(jù)庫(kù)。 讓我們創(chuàng)建一個(gè)athomes的表,為什么是athomes,因?yàn)橐郧霸趯慳ndroid程序的時(shí)候就叫的是athome,忽略掉這些將要的因素吧。

php artisan migrate:make create_athomes_table

打開 app/database/create_athomes_table.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是自加的,也就是我們?cè)趌ocalhost/athome/{id},當(dāng)我們創(chuàng)建一個(gè)新的數(shù)據(jù)的時(shí)候,會(huì)自動(dòng)加上去,最后一個(gè)timestamps批的是時(shí)間,會(huì)包含創(chuàng)建時(shí)間和修改時(shí)間。 剩下的temperature,sensors1,sensors2是小數(shù),以及只有真和假的led1。

數(shù)據(jù)庫(kù)遷移

我們只是寫了我們需要的數(shù)據(jù)的格式而并沒(méi)有丟到數(shù)據(jù)庫(kù)里,

php artisan migrate

這個(gè)就是我們執(zhí)行遷移的命令,如果你用phpmyadmin可以直接打開查看,沒(méi)有的話,可以。

mysql -uroot -p
use iot;
select * from athomes;

就可以看到我們寫的東西,那么接下來(lái)就是創(chuàng)建RESTful 服務(wù)了

創(chuàng)建RESTful

用下面的代碼實(shí)現(xiàn)我們稱之為Athomes控制器的創(chuàng)建

php artisan controller:make AthomesController

就會(huì)在app/controllers下面生成下面的代碼

    class AthomesController extends \BaseController {  
        /** 
         * Display a listing of the resource. 
         * 
         * @return Response 
         */  
        public function index()  
        {  
            //  
        }  
        /** 
         * Show the form for creating a new resource. 
         * 
         * @return Response 
         */  
        public function create()  
        {  
            //  
        }  
        /** 
         * Store a newly created resource in storage. 
         * 
         * @return Response 
         */  
        public function store()  
        {  
            //  
        }  
        /** 
         * Display the specified resource. 
         * 
         * @param  int  $id 
         * @return Response 
         */  
        public function show($id)  
        {  
            //  
        }  
        /** 
         * Show the form for editing the specified resource. 
         * 
         * @param  int  $id 
         * @return Response 
         */  
        public function edit($id)  
        {  
            //  
        }  
        /** 
         * Update the specified resource in storage. 
         * 
         * @param  int  $id 
         * @return Response 
         */  
        public function update($id)  
        {  
            //  
        }  
        /** 
         * Remove the specified resource from storage. 
         * 
         * @param  int  $id 
         * @return Response 
         */  
        public function destroy($id)  
        {  
            //  
        }  
    } 

Laravel Resources

上面的代碼過(guò)于沉重,請(qǐng)讓我用Ctrl+C來(lái)帶來(lái)點(diǎn)知識(shí)吧。。

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

所以我們只需要專注于創(chuàng)建create,edit,show,destory,等等。好吧,你可能沒(méi)有耐心了,但是在修改這個(gè)之前我們需要先在 app/model加個(gè)class

    class Athomes extends Eloquent {  
        protected $table = 'athomes';  
    } 

如果你想要的只是控制器Athomes的代碼的話。。

class AthomesController extends \BaseController {
        /
         * Display a listing of the resource.
         * @return Response
         /
        public $restful=true;
        protected $athome;
        public function __construct(Athomes $athome)
        {
            $this->athome = $athome ;
         }
        public function index()
        {
            $maxid=Athomes::all();
            return Response::json($maxid);
        }
        /
         * Show the form for creating a new resource.
         * @return Response
         /
        public function create()
        {
            $maxid=Athomes::max('id');
            return View::make('athome.create')->with('maxid',$maxid);
        }
        /
         * Store a newly created resource in storage.
         * @return Response
         /
        public function store()
        {
            // validate
            // read more on validation at http://laravel.com/docs/validation
            $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);
            // process the login
            if ($validator->fails()) {
                return Redirect::to('athome/create')
                    ->withErrors($validator)
                    ->withInput(Input::except('password'));
            } 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();
                // redirect
                Session::flash('message', 'Successfully created athome!');
                return Redirect::to('athome');
            }
        }
        /
         * Display the specified resource.
         * @param  int  $id
         * @return Response
         /
        public function show($id)
        {
            $myid=Athomes::find($id);
            $maxid=Athomes::where('id','=',$id)
                            ->select('id','temperature','sensors1','sensors2','led1')
                            ->get();
            return Response::json($maxid);
        }
        /
         * Show the form for editing the specified resource.
         * @param  int  $id
         * @return Response
         /
        public function edit($id)
        {
            // get the nerd
            $athome = Athomes::find($id);
            // show the edit form and pass the nerd
            return View::make('athome.edit')
                ->with('athome', $athome);
        }
        /
         * Update the specified resource in storage.
         * @param  int  $id
         * @return Response
         /
        public function update($id)
        {
            // validate
            // read more on validation at http://laravel.com/docs/validation
            $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);
            // process the login
            if ($validator->fails()) {
                return Redirect::to('athome/' . $id . '/edit')
                    ->withErrors($validator);
            } else {
                // store
                $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();
                // redirect
                Session::flash('message', 'Successfully created athome!');
                return Redirect::to('athome');
            }
        }
        /
         * Remove the specified resource from storage.
         * @param  int  $id
         * @return Response
         /
        public function destroy($id)
        {
            // delete
            $athome = Athomes::find($id);
            $athome->delete();
            if(is_null($athome))
            {
                 return Response::json('Todo not found', 404);
            }
            // redirect
            Session::flash('message', 'Successfully deleted the nerd!');
            return Redirect::to('athome');
        }
    }

希望你能讀懂,沒(méi)有的話,關(guān)注下一節(jié)。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)