`
sillycat
  • 浏览: 2486078 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

PHP(8)RESTful - Model Route Controller - Simple Example

 
阅读更多
PHP(8)RESTful - Model Route Controller - Simple Example

All the sample and details are in project easyphprest project.

1. Model
I am using the default things, so I directly create a Class named Book under app/Book.php
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{

     protected $fillable = ['title', 'author', 'isbn'];

}
?>

2. Route
Under directory app/Http/, there is a file routes.php, It will take care of all the routes configurations.

$app->get('/', function() use ($app) {
    return $app->welcome();
});

$app->group(['prefix' => 'api/v1', 'namespace' => 'App\Http\Controllers'], function($app){
    $app->get('book', 'BookController@index');
    $app->get('book/{id}', 'BookController@getbook');
    $app->post('book', 'BookController@createBook');
    $app->put('book/{id}', 'BookController@updateBook');
    $app->delete('book/{id}', 'BookController@deleteBook');
});

It will mapping all the requests to Controller, formatted and received all the parameters. That is exactly what the framework should do for us. It is quite similar to other frameworks in java/scala/python.

3. Controller
The actually controller is app/Http/Controllers/BookController.php

<?php

namespace App\Http\Controllers;

use App\Book;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BookController extends Controller{

public function index(){
     $Books = Book::all();
     return response()->json($Books);
}

public function getBook($id){
     $Book = Book::find($id);
     return response()->json($Book);
}

public function createBook(Request $request){
     $Book = Book::create($request->all());
     return response()->json($Book);
}

public function deleteBook($id){
     $Book = Book::find($id);
     $Book->delete();

     return response()->json('deleted');
}

public function updateBook(Request $request, $id){
     $Book = Book::find($id);

     $Book->title = $request->input('title');
     $Book->author = $request->input('author');
     $Book->isbn = $request->input('isbn');
     $Book->save();

     return response()->json($Book);
}

}
?>

That is just basic implementation, we may need validation and other logic there. The good things is that there is the simple ORM in this framework as well. I did not take care of any DAO logic now.

Command to start our service
> php artisan serve

Then, we can directly use POST man to test all our things.
I do not know how long this shared link will work, I will just paste it here.
https://www.getpostman.com/collections/e3273823c70a058eedfe

References:
http://coderexample.com/restful-api-in-lumen-a-laravel-micro-framework/
http://sillycat.iteye.com/blog/2238841
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics