承接 farshidrezaei/vandar-responder 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

farshidrezaei/vandar-responder

Composer 安装命令:

composer require farshidrezaei/vandar-responder

包简介

Vandar Responder Laravel Packagee

README 文档

README

Installation

composer

composer require farshidrezaei/vandar-responder

you must publish config and languages files:

#config
php artisan vendor:publish --provider="FarshidRezaei\VandarResponder\Providers\ResponderServiceProvider" --tag="config"

#language
php artisan vendor:publish --provider="FarshidRezaei\VandarResponder\Providers\ResponderServiceProvider" --tag="language"

after publish config file you can customize string errors. string errors will use in failure responses.

you can access errors like bellow:

config('responder.errors.YOUR_ERROR')
config('responder.errors.INTERNAL_ERROR')
config('responder.errors.EXTERNAL_SERVICE_ERROR')

you can access translation like bellow:

__('responder::exceptions.YOUR_ERROR')
__('responder::exceptions.validation')

Usage

Signatures of methods:

Responder::success(?string $message = null, mixed $data = null): Illuminate\Http\JsonResponse

Responder::successResourceCollection(null|string $message = null, Illuminate\Http\Resources\Json\AnonymousResourceCollection $data) :lluminate\Http\Resources\Json\AnonymousResourceCollection

Responder::failure(int $errorCode, string $stringErrorCode, null|string $message = null, array|null $errors = [], array|null $data = []): Illuminate\Http\JsonResponse

Here's a quick example:

You can use function added macro on response class:

// php 8
return response()->failure(
            errorCode: Response::HTTP_INTERNAL_SERVER_ERROR,// 500
            stringErrorCode: config('responder.errors.INTERNAL_ERROR'),
            message: "Service isn't available now. try again later.",
            data:['foo'=>'bar']
        );

Or call function from facade directly:

use FarshidRezaei\VandarResponder\Services\Responder;

// php 8
 return Responder::failure(
            errorCode: Response::HTTP_INTERNAL_SERVER_ERROR,// 500
            stringErrorCode: config('responder.errors.INTERNAL_ERROR'),
            message: "Service isn't available now. try again later.",
            data:['foo'=>'bar']
        );


// php 7.4
 return Responder::failure(
            Response::HTTP_INTERNAL_SERVER_ERROR,// 500
            config('responder.errors.INTERNAL_ERROR'),
            "Service isn't available now. try again later.",
            ['foo'=>'bar']
        );

And you will get bellow response:

{
  "message": "Service isn't available now. try again later.",
  "code": "internal_error",
  "data": {
        "foo":"bar"
  }
}

Also you can use responder() helper function :

// php 8
 return responder()->success(
                message:"User Info",
                data: [
                    "name"=>"Farshid",
                    "company"=>"Vandar",
                    "Position"=>"Full-Stack Web Developer"
                ]
        );

and you will get bellow response:

{
    "message": "User Info",
    "data": {
        "name": "Farshid",
        "company": "Vandar",
        "Position": "Full-Stack Web Developer"
    }
}

if you want to respond laravel ResourceCollection do like bellow:

// php 8
    $users=User::paginate();
    return Responder::successResourceCollection(
        message: 'User List.',
        data: USerResource::collection($users)
    );

Api Exception Handler

To standardize the responses, the exceptions must also follow vandar standards. laravel has itself rules to show response of exceptions. with this feature of this package you can customize every laravel exceptions.

for use this feature please add bellow code to render() function in app/Exceptions/Handler.php:

    public function render($request, Throwable $e): \Illuminate\Http\Response|JsonResponse|Response
    {
        //...
        if ($request->expectsJson() && $exceptionResponse = ApiExceptionHandler::handle($e)) {
            return $exceptionResponse;
        }
        //...
        return parent::render($request, $e);
    }

we handle and customize some exceptions. after publish configs, you can see it in config/responder.php as customExceptions key:

  'customExceptions' => [
        RuntimeException::class => CustomDefaultException::class,
        Exception::class => CustomDefaultException::class,
        ValidationException::class => CustomValidationException::class,
        NotFoundHttpException::class => CustomNotFoundHttpException::class,
        MethodNotAllowedException::class => CustomMethodNotAllowed::class,
        ModelNotFoundException::class => CustomNotFoundHttpException::class,
        AuthenticationException::class => CustomAuthenticationException::class,
        AuthorizationException::class => CustomUnauthorizedException::class,
        UnauthorizedHttpException::class => CustomUnauthorizedException::class,
        ThrottleRequestsException::class => CustomThrottleRequestsException::class
    ]

you can customize,add,edit and override any of classes.

also you can publish this classes by run this command:

#customExceptions
php artisan vendor:publish --provider="FarshidRezaei\VandarResponder\Providers\ResponderServiceProvider" --tag="customExceptions"

don't forget change namespace of classes after publish

customException structure

class CustomDefaultException extends AbstractApiCustomException implements ApiCustomExceptionInterface
{
    public function __construct(?Exception $exception)
    {
        $this->errorCode = Response::HTTP_INTERNAL_SERVER_ERROR; // exception Status Code

        $this->stringErrorCode = config('responder.errors.EXTERNAL_SERVICE_ERROR'); // string error code

        $this->errorMessage = __('responder::exceptions.generalServerError'); // message of error

        parent::__construct();
    }
}

if you assign it for a laravel exception it will call responder failure() function and return json response to client.

//with status 500
{
    "message": "خطایی رخ داده است، لطفا دوباره تلاش کنید",
    "code": "external_service_error"
}

tip

if you want to create a non-laravel exception and throw it, you can call Responder::failure() function in render of exception.

it will return standard json.

License

The MIT License (MIT). Please see License File for more information.

farshidrezaei/vandar-responder 适用场景与选型建议

farshidrezaei/vandar-responder 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10.19k 次下载、GitHub Stars 达 5, 最近一次更新时间为 2022 年 07 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 farshidrezaei/vandar-responder 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 farshidrezaei/vandar-responder 我们能提供哪些服务?
定制开发 / 二次开发

基于 farshidrezaei/vandar-responder 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 10.19k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 5
  • 点击次数: 15
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-07-17