fake-fakers/laravel-api-components

一组有用的Laravel组件

1.0.1 2020-10-29 20:22 UTC

This package is not auto-updated.

Last update: 2024-09-28 16:10:19 UTC


README

组件列表

中间件

  1. PreferJson - 一个简单的中间件,可用于API路由,优先返回JSON响应而不是默认的HTML。还有一个选项,即使存在Accept头,也可以强制输出JSON。

辅助函数

  1. formatValidationErrors - 将ValidationException转换为数组。
  2. escapeStringForSqlLike - 转义字符串以用于SQL LIKE查询。

异常处理器

提供了一种简单的方法来定义应用程序的异常处理器。
使用方法

  1. 从本包的异常处理器继承 app/Exception/Handler.php
    use Brainex\ApiComponents\Exceptions\BaseHandler;
    
    class Handler extends BaseHandler
    {
       // write your code here
    }
  2. 定义自己的异常处理器
        /**
         * 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());
        }

服务提供者

  1. RoutingServiceProvider - 覆盖Laravel的默认Router和ResponseFactory,以返回带有JSON_UNESCAPED_UNICODE的JSON响应。
    使用方法
    1. 在您的应用文件夹中创建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));
          }
      }
    2. 修改bootstrap/app.php文件以创建新的Application类,而不是使用Laravel的默认类
      $app = new \App\Application(
          realpath(__DIR__.'/../')
      );