patricksavalle/slim-request-params 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

patricksavalle/slim-request-params

Composer 安装命令:

composer require patricksavalle/slim-request-params

包简介

Adds request-parameter validation to the SLIM 3.x PHP framework

README 文档

README

Needs PHP 7.x

Validates request query-parameters and body-parameters ($_GET and $_BODY) and HTTP-headers using regular expressions. Adds a layer of security and self-documentation to your API-code. Uses the same syntax as SLIM uses for route-segments.

Example:

use SlimRequestParams\QueryParameters;

$slimapp->get('', ...)
    ->add(new QueryParameters([
        '{text:\w+}',
        '{fromdate:\date}',
        '{distance:\float},0.0',
        '{orderby:(name|date)},name',
        '{reversed:\bool},false',
        '{offset:\int},1',
        '{count:\int},100',
    ]);

This would for example accept this request:

GET yourdomain.com?text=airplane&fromdate=2016-10-10

And it would for example reject these requests:

GET yourdomain.com?text=airplane&fromdate=2016-10-10&whatever=23
GET yourdomain.com?text=airplane&fromdate=date
GET yourdomain.com?fromdate=2016-10-10&whatever=23
GET yourdomain.com?text=airplane&
GET yourdomain.com

etc.

0. Install with Composer

  • Update your composer.json to require patricksavalle/slim-request-params.

  • Run composer install to add slim-request-params your vendor folder.

    {
      "require": {
        "patricksavalle/slim-request-params": "^1.0"
      }
    }
  • Include in your source.

    <?php
    
    require './vendor/autoload.php';

1. Add the middleware to the SLIM routes

To validate request parameters:

use SlimRequestParams\QueryParameters;

$slimapp->get(...)
    ->add(new QueryParameters([
        '{author:[\w-. @]+}',
        '{orderby:\w+},id',
        '{reversed:1},1',
        '{offset:\int},1',
        '{count:\int},100',
        '{*}',
    ])

To validate body parameters (posted by client as x-www-form-urlencoded):

use SlimRequestParams\BodyParameters;

$slimapp->post(...)
    ->add(new BodyParameters([
        '{recipient:.*}',
        '{sender:.*}',
        '{subject:.*}',
        '{timestamp:.*}',
        '{token:.*}',
        '{signature:.*}',
        '{*}',
    ]));

To validate request headers (make sure they are present and their values follows a specific pattern):

use SlimRequestParams\RequestHeaders;

$slimapp->post(...)
    ->add(new RequestHeaders([
        '{HTTP_REFERER:\url}',
        '{HTTP_CB_SIGNATURE:.*}',
    ]));

To forbid arguments to a route:

$slimapp->get(...)
    ->add(new QueryParameters)

General format of a validation rule:

{<name>:<regex>},<optional_default_value>

Missing parameters are set to the given default.

Explicitely setting a value to null:

/someurl?key=  (leave value empty) 

Extra parameters generate an error unless the wildcard parameter is used: {*} in which case the extra parameters are passed without validation.

Accepts the RFC-standard query parameter array, not the PHP version:

/someurl?a=10&a=11&a=12

For typed parameters and special formats there are the following keywords that can be used instead of the regex:

\boolean
\int
\float
\date
\raw
\base64json
\url
\email
\country
\nationality
\timezone
\currency
\language
\bitcoinaddress
\moneroaddress
\xtext   (a XHTML fragment only using text formatting tags, tidies up the text)

These are only syntax checks! Also there is an accept 'anything else' argument:

{*}

Optional parameters should get the default:

\optional

(See code example above)

The RequestHeaders Middleware always accept 'anything else'.

2. Install the strategy in SLIM3.x for access to the validated arguments

Add the strategy that combines the url-, query- and post-parameters and request-headers into one object.

$slimapp->getContainer()['foundHandler'] = function () {
    return new RequestResponseArgsObject;
};        

3. Adapt your route handlers to the new strategy

A complete example.

<?php

declare(strict_types = 1);

namespace YourApi;

define("BASE_PATH", dirname(__FILE__));

require BASE_PATH . '/vendor/autoload.php';

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \SlimRequestParams\BodyParameters;
use \SlimRequestParams\QueryParameters;
use \SlimRequestParams\RequestResponseArgsObject;

$app = new \Slim\App;

$app->getContainer()['foundHandler'] = function () {
    return new RequestResponseArgsObject;
};

$app->get('/hello/{name}', function (Request $request, Response $response, \stdClass $args) {
    $name = $args->name;
    $text = $args->text;
    $referer = $args->referer;
    $response->getBody()->write("$text, $name, $referer");
    return $response;
})
    ->add(new RequestHeaders(['{HTTP_REFERER:\url']))
    ->add(new QueryParameters(['{text:[\w-.~@]+},Hello']));

$app->run();

To retrieve or inspect the validated parameters from anywhere in your app just use:

\SlimRequestParams\QueryParameters::get();
\SlimRequestParams\BodyParameters::get();
\SlimRequestParams\RequestHeaders::get();

patricksavalle/slim-request-params 适用场景与选型建议

patricksavalle/slim-request-params 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.97k 次下载、GitHub Stars 达 9, 最近一次更新时间为 2016 年 12 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 patricksavalle/slim-request-params 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 1.97k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 11
  • 点击次数: 11
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 9
  • Watchers: 2
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-12-02