承接 juanchosl/requestlistener 相关项目开发

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

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

juanchosl/requestlistener

Composer 安装命令:

composer require juanchosl/requestlistener

包简介

Little methods collection in order to create an APP listener, that can be able to receive, process and response to http request and cli commands

README 文档

README

Description

This library groups the definitions of the different elements involved in data transmissions such as HTTP, applying the interfaces defined in PSRS 7 and 17, adding the extra objects used and ensuring compliance with the requirements that allow to give the necessary stability To our application, being able to implement for third -party bookstores without the need to adapt our business logic to a new implementation that could modify its consumption or internal structure.

Install

composer require juanchosl/requestlistener

Engines

The library accept two types of uses

  • http requests
  • console commands

Both systems parse the SERVER globals and create a ServerRequestInterface compatible element in order to unify his use across all the work flow. The user needs to prepare the response format according to the requested type. You can create you own Engine parser implementing the JuanchoSL\Contracts\EnginesInterface, only needs:

  • static parse method, passing the vars to parse. Returns an EngineInterface entity
  • getRequest, to retrieve the parsed ServerRequest
  • sendMessage, to perform and send the compatible ResponseInterface message

HTTP requests

Create a request according to the PSR-7, the request is builded using PHP superglobals, for body contents, if content-type header is setted as application/x-www-form-urlencoded or multipart/form-data, the superglobal POST is used, for other media-types, the 'php://input' contents is readed and putted as body and parsed as a DataTranster entity and putted into parsedBody

Console commands

Create a request according to the PSR-7, the request is builded using SERVER['args'] superglobal for fill Query params and STDIN for body contents, the arguments need to have the next format: The parameter name needs to start with --, then can assign values from:

  • concat with an equals sign (--name=value)
  • put the value after parameter (--name value)
  • if is a void parameter that don't need value, just write the parameter name (--void_parameter)
  • if is a multiple values parameter, use the name all times that you need pass a value or write the name and value multiple times as a single value
    • --multiple=value1 --multiple=value2
    • --multiple value1 --multiple value2
    • --multiple value1 value2

Application

Middlewares

PRE middlewares

Enabled by default
  • ValidRouteMiddleware: Check than the selected target is defined and exists
  • OptionsMethodMiddleware: Return a response with the available METHODs for the selected target
  • TraceMethodMiddleware: Check if the TRACE method is available for the selected target
  • HeadMethodMiddleware: If the request is a HEAD method request, convert to GET, process it and remove the body before return to client
Available for use
  • ValidMethodMiddleware: Check if the requested method is available, if a HEAD method is selected, we convert to a GET before check it, and remove the body from response if it is availble
  • ValidMediaTypeMiddleware: Check if any accepted media-type from the request is available
  • CacheMiddleware: Can enable this available middleware providing a PSR-16 SimpleCacheInterface in order to use it
  • OutputCompressionMiddleware: Using this available middleware, can compress or encodig response bodies, accord the Accept-Encoding client header, in br(brotli), zstd, deflate or gzip
  • RateLimitMiddleware: In order to count the UNAUTHORIZED responses and block the client using SESSION for N seconds, can indicate the num of failed counts and the banned seconds

User Defined PRE middlewares

You can create and use Middlewares that implementing the PSR-15 Interfaces, according the Psr\Http\Server\MiddlewareInterface

<?php declare(strict_types=1);

namespace Src\Infrastructure\Middlewares;

use Fig\Http\Message\StatusCodeInterface;
use JuanchoSL\HttpData\Factories\ResponseFactory;
use JuanchoSL\Validators\Types\Strings\StringValidations;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;

class AuthorizationMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $ip = filter_input(INPUT_SERVER, 'SERVER_ADDR');
        if (!(new StringValidations)->isNotEmpty()->isIpV4()->isValueContaining('192.168.0.1')->getResult((string)$ip)) {
            return (new ResponseFactory)->createResponse(StatusCodeInterface::STATUS_UNAUTHORIZED);
        }
        return $handler->handle($request);
    }
}

Other available Middlewares

  • CacheMiddleware: Use any compatible PSR-16 library in order to check, load and save web caches
  • OutputCompressionMiddleware: Compress http responses using native libraries (deflate and gzip)
  • DebugXhprofMiddleware

Request handlers

According the PSR-15, you can create and execute your own RequestHandlers

<?php declare(strict_types=1);

namespace JuanchoSL\RequestListener\Commands;

use Fig\Http\Message\StatusCodeInterface;
use JuanchoSL\DataTransfer\Factories\DataConverterFactory;
use JuanchoSL\DataTransfer\Factories\DataTransferFactory;
use JuanchoSL\HttpData\Factories\ResponseFactory;
use JuanchoSL\HttpData\Factories\StreamFactory;
use JuanchoSL\HttpHeaders\ContentType;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class ConvertHandler implements RequestHandlerInterface
{

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $body_contents = DataTransferFactory::byMimeType((string) $request->getBody(), $request->getHeader('content-type'));
        $content_type = ($request->hasHeader('accept')) ? $request->getHeader('accept') : ContentType::get($request->getQueryParams()['format']);
        $body = DataConverterFactory::asMimeType($body_contents, $content_type);

        return (new ResponseFactory)->createResponse(StatusCodeInterface::STATUS_OK)
            ->withAddedHeader('content-type', $content_type)
            ->withBody((new StreamFactory)->createStream($body));
    }
}

Use cases

The Application system, group the routing, methods access, and callables to be executed when the rules has been accomplished. Into the entrypoint, you need to prepare endpoints and his rules to be executed.

When you extend the UseCases provided class, a configure method is required, in order to set the valid parameters, performing an autovalidation

The callables can be:

  • A Handler implementing the PSR-15 interface
  • A command, extending the UseCases provided class and implementing an __invoke method with the params:
    • ServerRequestInterface
    • ResponseInterface
  • A callable with format [Class, 'method_to_call']
<?php

use JuanchoSL\Logger\Logger;
use JuanchoSL\Logger\Composers\TextComposer;
use JuanchoSL\Logger\Repositories\FileRepository;
use JuanchoSL\RequestListener\Application;
use JuanchoSL\RequestListener\Handlers\MyErrorHandler;
use JuanchoSL\RequestListener\Middlewares\AuthenticationMiddleware;
use JuanchoSL\RequestListener\Middlewares\OutputCompressionMiddleware;

date_default_timezone_set("Europe/Madrid");

include_once dirname(__FILE__, 2) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
$logger = new Logger((new FileRepository(implode(DIRECTORY_SEPARATOR, ['..', 'logs', 'error.log'])))->setComposer(new TextComposer));
$errorHandler = (new MyErrorHandler)->setLogErrors(true)->setLogErrorsDetails(true)->setDisplayErrorsDetails(true);
$errorHandler->setLogger($logger);

$app = new Application();
$app->setErrorHandler($errorHandler);
$app->addMiddleware(new AuthenticationMiddleware);
$app->post('/convert', ConvertCommand::class);
$app->put('/convert', ConvertHandler::class);
$app->addMiddleware(new OutputCompressionMiddleware);
$app->run(); //call to run, performs an exit in order to process shutdown_functions and exit code from console use

ExampleCommand

<?php declare(strict_types=1);

namespace JuanchoSL\RequestListener\Commands;

use Fig\Http\Message\StatusCodeInterface;
use JuanchoSL\DataTransfer\Factories\DataConverterFactory;
use JuanchoSL\DataTransfer\Factories\DataTransferFactory;
use JuanchoSL\HttpData\Factories\StreamFactory;
use JuanchoSL\HttpHeaders\ContentType;
use JuanchoSL\RequestListener\Enums\InputArgument;
use JuanchoSL\RequestListener\Enums\InputOption;
use JuanchoSL\RequestListener\UseCases;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class ConvertCommand extends UseCases
{
    protected function configure(): void
    {
        $this->addArgument('format', InputArgument::OPTIONAL, InputOption::SINGLE);
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $body_contents = DataTransferFactory::byMimeType((string) $request->getBody(), $request->getHeader('content-type'));
        $content_type = ($request->hasHeader('accept')) ? $request->getHeader('accept') : ContentType::get($request->getQueryParams()['format']);
        $body = DataConverterFactory::asMimeType($body_contents, $content_type);

        return $response
            ->withStatus(StatusCodeInterface::STATUS_OK)
            ->withAddedHeader('content-type', $content_type)
            ->withBody((new StreamFactory)->createStream($body));
    }
}

Debug

juanchosl/requestlistener 适用场景与选型建议

juanchosl/requestlistener 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 173 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 05 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「http」 「stream」 「console」 「response」 「message」 「uri」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

围绕 juanchosl/requestlistener 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 173
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 18
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-05-21