dilneiss/ laravel-api-tool-kit
使用 Laravel 构建API的工具集
Requires
- php: ^7.4|^8.0
- illuminate/support: ^6.20.13|7.30.4|^8.22.2|^9.0
README
Laravel api tool kit 是一套工具,可以帮助您使用 Laravel 最佳实践快速构建一个高效且井然有序的 API。
内容
安装
composer require essa/api-tool-kit
发布配置
php artisan vendor:publish --provider="Essa\APIToolKit\APIToolKitServiceProvider" --tag="config"
使用异常处理器标准化错误响应 错误响应
在 App\Exceptions\Handler 类中扩展 APIHandler 类
namespace App\Exceptions; use Essa\APIToolKit\Exceptions\Handler as APIHandler; class Handler extends APIHandler { }
在控制器中使用 API 响应特性
App\Http\Controllers\Controller.php
:
use Essa\APIToolKit\Api\ApiResponse; class Controller extends BaseController { use ApiResponse; }
检查:API 响应
API 响应
用于格式化响应为标准格式和状态码,对于成功响应,它将是
成功响应
{ "message": "your message", "data": "your date" }
错误响应
{ "errors": [ { "status": 403, "title": "unauthenticated!", "detail": "Unauthenticated." } ] }
使用:您可以在想要返回响应的类内部使用特性
并按如下方式使用
$this->responseSuccess('car created successfully' , $car);
可用方法
responseSuccess($message , $data) // returns a 200 HTTP status code responseCreated($message,$data) // returns a 201 HTTP status code responseDeleted() // returns empty response with a 204 HTTP status code responseNotFound($error_details,$error_title) // returns a 404 HTTP status code responseBadRequest($error_details,$error_title) // returns a 400 HTTP status code responseUnAuthorized($error_details,$error_title) // returns a 403 HTTP status code responseConflictError($error_details,$error_title) // returns a 409 HTTP status code responseUnprocessable($error_details,$error_title) // returns a 422 HTTP status code responseUnAuthenticated ($error_details,$error_title) // returns a 401 HTTP status code responseWithCustomError($error_title, $error_details, $status_code) //send custom error
动态分页
动态使用分页
使用
要使用动态分页获取所有用户
$users = User::dynamicPaginate();
获取所有用户,不使用分页
\users?pagination='none'
获取所有用户,每页10个用户
\users?per_page=10
默认情况下,分页为每页20个元素,您可以从 config/api-tool-kit 中更改默认值
过滤器
使用
创建一个过滤器类
php artisan make:filter CarFilters
将默认过滤器设置到 Car 模型中,在 Car 模型中,您将添加
protected $default_filters = CarFilters::class;
使用它
Car::useFilters()->get();
如果您想覆盖默认过滤器
Car::useFilters(SpecialCaseCarFilters::class)->get();
过滤器类中的选项
//to add the attributes to filter by =>> /cars?color=red&model_id=1 protected array $allowedFilters = ['color' , 'model_id']; //to add the attributes to filter by : // desc : ?sorts=created_at // asc : ?sorts=-created_at protected array $allowedSorts= ['created_at']; // allowed relationships to be loaded // ?includes=model protected array $allowedIncludes = ['model']; //column that will be included in search =>> ?search=tesla protected array $columnSearch= ['name','descriptions']; //relation that will be included in search =>> ?search=ahmed protected array $relationSearch = [ 'user' => ['first_name', 'last_name'] ];
创建一个自定义查询,您只需在类中创建一个新的函数并添加您的查询示例,按年份筛选
public function year($term) { $this->builder->whereYear('created_At', $term); } //usage : /cars?year=2020
按关系筛选
public function option($term) { $this->builder->whereHas('options', fn($query) => $query->where('option_id', $term)); } //usage : /cars?option=1
API 生成器
使用
php artisan api:generate Car
当您输入命令时,它会询问您是否想要默认选项
- (N) 它将询问您想要生成哪些文件
- (Y) 它将生成 config/api-tool-kit 中存在的所有选项的文件
选项
** by default it will create a model :
-app/Models/Car.php
** controller :
-app/Http/Controllers/API/CarController.php
** resource :
-app/Http/Resources/CarResource.php
** request :
-app/Http/Requests/Car/CreateCarRequest.php
-app/Http/Requests/Car/UpdateCarRequest.php
** filter :
-app/Filters/CarFilters.php
** seeder :
-database/seeders/CarSeeder.php
** factory :
-database/factories/CarFactory.php
** test :
-Tests/Feature/CarTest.php
** migration :
-database/migrations/x_x_x_x_create_cars_table.php
此外,路由将在 routes/api.php 文件中创建并添加
操作
操作是 Laravel 对命令设计模式的实现,它创建一个类,您可以在其中添加您的业务逻辑 https://en.wikipedia.org/wiki/Command_pattern
使用
php artisan make:action CreateCar
<?php namespace App\Actions; class CreateCar { public function execute($data) { //add business logic to create a car } }
使用操作类的最佳实践是使用依赖注入
您有很多选择 1-使用 Laravel 应用容器
app(CreateCar::class)->execute($data);
2-在构造函数中注入它
private $create_car_action ; public function __construct(CreateCar $create_car_action) { $this->create_car_action=$create_car_action; } public function doSomething() { $this->create_car_action->execute($data); }
3-在 Laravel 控制器函数中注入它
public function doSomething(CreateCar $create_car_action) { $create_car_action->execute($data); }
媒体助手
用于上传和删除存储中的文件
// to upload file $file_path = MediaHelper::uploadFile($file ,$path); //to delete an file MediaHelper::deleteFile($path); //upload multiple files $files_paths = MediaHelper::uploadMultiple($files ,$path); //upload base64 image $image_path = MediaHelper::uploadBase64Image($encoded_image ,$path);
**枚举**
不良实践:如果有两种用户类型(管理员、学生),每次使用时都不应硬编码用户类型的名称,而应简单地使用枚举类
使用
php artisan make:enum UserTypes
它将生成如下类
namespace App\Enums; class UserTypes extends Enum { public const ADMIN = 'admin'; public const STUDENT = 'student'; }
方法
UserTypes::getAll() //get all types UserTypes::isValid($value) //to check if this value exist in the enum UserTypes::toArray() //to get all enums as key and value
通用技巧
抛出错误而不是返回 JSON 响应
不良
public function index() { if (auth()->user()->not_active ) { $this->responseUnAuthorized('you can not preform this action'); } }
良好
public function index() { if (auth()->user()->not_active ) { throw new AuthorizationException('you can not preform this action'); } }