fake-fakers / laravel-api-components
一组有用的Laravel组件
1.0.1
2020-10-29 20:22 UTC
Requires
- php: >=7.2
- ext-json: *
- laravel/framework: 5.6.*|5.7.*|5.8.*|6.*|7.*|8.*
- symfony/psr-http-message-bridge: ~1.0
This package is not auto-updated.
Last update: 2024-09-28 16:10:19 UTC
README
组件列表
中间件
PreferJson
- 一个简单的中间件,可用于API路由,优先返回JSON响应而不是默认的HTML。还有一个选项,即使存在Accept头,也可以强制输出JSON。
辅助函数
formatValidationErrors
- 将ValidationException转换为数组。escapeStringForSqlLike
- 转义字符串以用于SQL LIKE查询。
异常处理器
提供了一种简单的方法来定义应用程序的异常处理器。
使用方法
- 从本包的异常处理器继承
app/Exception/Handler.php
类use Brainex\ApiComponents\Exceptions\BaseHandler; class Handler extends BaseHandler { // write your code here }
- 定义自己的异常处理器
/** * A list of custom exception handlers * * @return array */ protected function getCustomHandlers(): array { return [ OAuthServerException::class => [$this, 'oauthServerJson'] ]; } /** * Get JsonResponse for OAuthServerException exception * * @param OAuthServerException $exception * @return JsonResponse */ protected function oauthServerJson(OAuthServerException $exception): JsonResponse { return \response()->json([ 'message' => $exception->getErrorType(), 'data' => [ 'description' => $exception->getMessage(), 'hint' => $exception->getHint() ] ], $exception->getHttpStatusCode(), $exception->getHttpHeaders()); }
服务提供者
RoutingServiceProvider
- 覆盖Laravel的默认Router和ResponseFactory,以返回带有JSON_UNESCAPED_UNICODE
的JSON响应。
使用方法- 在您的应用文件夹中创建
Application
类declare(strict_types=1); namespace App; use Illuminate\Log\LogServiceProvider; use Illuminate\Events\EventServiceProvider; /** * Class Application * @package App * * Overriding original application to hook router */ class Application extends \Illuminate\Foundation\Application { /** * Register all of the base service providers. * * @return void */ protected function registerBaseServiceProviders(): void { $this->register(new EventServiceProvider($this)); $this->register(new LogServiceProvider($this)); // hook responses to make them JSON_UNESCAPED_UNICODE $this->register(new \Brainex\ApiComponents\Routing\RoutingServiceProvider($this)); } }
- 修改
bootstrap/app.php
文件以创建新的Application
类,而不是使用Laravel的默认类$app = new \App\Application( realpath(__DIR__.'/../') );
- 在您的应用文件夹中创建