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

本文介绍了一个基于PHP的RESTful API实现示例,包括模型、路由配置及控制器的基本实现方式。通过具体代码展示了如何创建、读取、更新及删除图书记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值