logcomex/php-utils

适用于Lumen和Laravel项目的PHP工具

2.0.1 2022-10-04 21:18 UTC

This package is auto-updated.

Last update: 2024-09-13 16:14:25 UTC


README

PHP工具包(适用于Laravel/Lumen)

安装

cd /path/to/your/project
composer require logcomex/php-utils

工具包

  • 接口
  • 异常
  • 功能
  • 处理器
  • 助手
  • 日志记录器
  • 日志
  • 中间件
  • 提供者
  • 单例

接口

包含php-utils类和其他类使用的所有接口,您可以在项目中使用。

异常

包含php-utils类使用的所有异常。以及您可以在项目中使用的其他异常来区分错误类型。

ApiException

您可以使用此异常处理400范围内的所有异常http代码

ApiException(string $token,
			string $message, 
			int $httpCode = Response::HTTP_BAD_REQUEST, 
			Exception $previous = null)  

BadImplementationException

此异常表示开发者未注意或错误地执行了某种情况。

BadImplementationException(string $token,
            string $message,
			int $httpCode = Response::HTTP_INTERNAL_SERVER_ERROR, 
			Exception $previous = null)  

SecurityException

此异常用于指出您的应用程序中的某些安全问题。

SecurityException(string $token,
			string $message, 
			int $httpCode = Response::HTTP_FORBIDDEN, 
			Exception $previous = null)  

UnavailableServiceException

此异常用于指出您的或其他应用程序不可用。

UnavailableServiceException(string $token,
			string $message, 
			int $httpCode = Response::HTTP_FORBIDDEN, 
			Exception $previous = null)  

功能

它们是一组可以用于您的代码的有用特性

PropertiesExporterFunctionality

您可以使用此功能导出一个包含您类属性的数组

public static function properties(): array  

PropertiesAttacherFunctionality

您可以使用此功能将参数中传递的值附加到类属性中。

注意:要使用此功能,您需要在类中使用PropertiesExporterFunctionality。

public function attachValues(array $values): void

ValuesExporterToArrayFunctionality

您可以使用此功能轻松获取类的所有属性组成的数组。

注意:要使用此功能,您需要进行两件事

  1. 类必须实现Illuminate\Contracts\Support\Arrayable。
  2. 类必须使用PropertiesExporterFunctionality。
public function toArray()  

ValuesExporterToJsonFunctionality

您可以使用此功能轻松获取类的所有属性组成的Json。

注意:要使用此功能,您需要进行两件事

  1. 类必须实现Illuminate\Contracts\Support\Jsonable。
  2. 类必须使用PropertiesExporterFunctionality。
public function toJson()  

助手

它们是一组助手类和特性。

EnumHelper

这是一个为您的枚举类提供一些实用工具的特性。

use Logcomex\PhpUtils\Helpers\EnumHelper;

class ProductEnum
{
	user EnumHelper;
	public const EXAMPLE = 'example';
	public const EXAMPLE2 = 'example2';
}

$allProducts = ProductEnum::all();

日志记录器

此包的目的是提供所有日志记录器类。

LogcomexLogger

使用此类可以轻松提供日志模板,这对于与Datadog集成非常重要。

// bootstrap/app.php

$app->register(Logcomex\PhpUtils\Providers\LogcomexLoggerProvider::class);

$app->withFacades(true, [
    Logcomex\PhpUtils\Facades\Logger::class => 'Logger',
]);

Logger::info('TOKEN-001', ['reason' => 'test',]);

中间件

它们是一组中间件类。

AuthenticateMiddleware

这是一个提供身份验证验证的类。您需要配置应用程序中的 AuthProvider 才能使用此中间件。

// bootstrap/app.php
$app->register(Your\Provider\AuthServiceProvider::class);

// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\AuthenticateMiddleware::class,
]);

// Or, by specific route
$app->routeMiddleware([
    'auth' => Logcomex\PhpUtils\Middlewares\AuthenticateMiddleware::class,
]);

RequestLogMiddleware

这是一个为您的api中的每个请求提供日志的类。您可以选择在日志中打印什么,例如:请求头、请求服务器、请求负载、响应头、响应内容、响应时间和跟踪ID。

.env配置

// config/requestLog.php
return [
    'enable-request-header' => env('REQUEST_LOGGER_ENABLE_REQUEST_HEADER', true),
    'enable-request-server' => env('REQUEST_LOGGER_ENABLE_REQUEST_SERVER', true),
    'enable-request-payload' => env('REQUEST_LOGGER_ENABLE_REQUEST_PAYLOAD', true),
    'enable-response-header' => env('REQUEST_LOGGER_ENABLE_RESPONSE_HEADER', true),
    'enable-response-content' => env('REQUEST_LOGGER_ENABLE_RESPONSE_CONTENT', true),
    'enable-response-time' => env('REQUEST_LOGGER_ENABLE_RESPONSE_TIME', true),
    'allowed-data-request-server' => explode(';', env('REQUEST_LOGGER_ALLOWED_DATA_REQUEST_SERVER', '')),
];


// bootstrap/app.php
$app->configure('requestLog');

// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\TracerMiddleware::class, // If you gonna use tracer, it must be above the requestlog
    Logcomex\PhpUtils\Middlewares\RequestLogMiddleware::class, // And after trace, you need the request log
]);

ResponseTimeLogMiddleware

这是一个注册您api中每个请求的响应时间的类。您可以通过调用中间件按路由选择要测量的请求。

首先,您必须在全球范围内在bootstrap之前定义框架的启动时间

// bootstrap/app.php
if (!defined('GLOBAL_FRAMEWORK_START')) {
    define('GLOBAL_FRAMEWORK_START', microtime(true));
}

配置

您的app配置必须包含键 'api-name',该键将由此中间件用于标识响应时间属于哪个API。

// bootstrap/app.php
$app->configure('app');

使用

非常重要,您必须首先调用此中间件,以确保响应时间计算尽可能准确。

// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\ResponseTimeLogMiddleware::class,
]);

// Using in specific routes
$app->routeMiddleware([
    'response-time-log' => Logcomex\PhpUtils\Middlewares\ResponseTimeLogMiddleware::class,
]);
Route::group(
    [
        'prefix' => 'example',
        'middleware' => ['response-time-log'],
    ],
    function () {
        Route::get('responseTimeLog', 'ExampleClassName@exampleMethodName');
    });

TracerMiddleware

这是一个提供API追踪功能的类。因此,您的日志可以使用这个值和HttpHelper。您必须在config文件夹中创建一个tracer配置文件。我们建议将此中间件作为全局使用,并在中间件链中的第一个。

// config/tracer.php
return [
    'headersToPropagate' => explode(';', env('TRACER_HEADERS_TO_PROPAGATE')),
];


// bootstrap/app.php
$app->configure('tracer');

// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\TracerMiddleware::class,
    // the other middlewares
]);

// Or, by specific route
$app->routeMiddleware([
    'tracer' => Logcomex\PhpUtils\Middlewares\TracerMiddleware::class,
]);

AccreditedApiKeysMiddleware

这是一个为您的API提供第一层安全性的类。最好的类比是中间件就是您的“API客人名单”。

您需要注册一个名为accreditedApiKeys的配置文件,其中包含可以请求您的API的所有API密钥。

因此,如果请求不包含x-infra-key头或允许的值,API将使用安全异常拒绝请求。

建议将其作为全局中间件使用,如果需要避免某些路由使用此中间件,只需将其插入到公共路由组中。

// config/accreditedApiKeys.php
return [
    'api-1' => env('API_1_X_API_KEY'),
    'api-2' => env('API_2_X_API_KEY'),
    'api-3' => env('API_3_X_API_KEY'),
];


// bootstrap/app.php
$app->configure('accreditedApiKeys');

// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\AccreditedApiKeysMiddleware::class,
]);


// routes/api.php
$router->group(['prefix' => 'public',], function () use ($router) {
    $router->get('test', 'Controller@test');// this route does not need x-infra-key validation
});

提供者

这个包的目的是提供一些提供者。为了更好地理解: Lumen Providers

LogcomexLoggerProvider

当您使用Logger Facade时,必须使用此提供者。

// bootstrap/app.php

$app->register(Logcomex\MicroservicesCore\Providers\LogcomexLoggerProvider::class);

## Singletons  

> They're a pack of Singleton classes.

#### TracerSingleton

> It is a class that provides the tracer value.

## Unit Tests Coverage

Master <br>
[![codecov](https://codecov.io/gh/comexio/php-utils/branch/master/graph/badge.svg)](https://codecov.io/gh/comexio/php-utils)

## TODO

 - [ ] HttpHelper Doc
 - [ ] TokenHelper Doc
 - [ ] Handlers Package Doc
	 - [ ] ExceptionHandler Doc
 - [ ] Logs Package Doc
	 - [ ] RequestLog Doc
 - [ ] Middlewares Package Doc
	 - [ ] AllowedHostsMiddleware Doc
	 - [ ] CorsMiddleware Doc

## Contributing  
  
- Open an issue first to discuss potential changes/additions.
- Open a pull request, you need two approvals and tests need to pass Travis CI.