icanhazstring/expressive-hashids-middleware

遵守PSR-15/PSR-7规范的中间件,使用ivanakimov/hashids.php

v1.0 2018-05-23 11:45 UTC

This package is auto-updated.

Last update: 2024-08-26 02:18:15 UTC


README

遵守PSR-15/PSR-7规范的中间件,使用ivanakimov/hashids.php

Build Status Code Climate Test Coverage

安装

您可以使用composer安装expressive-hashids-middleware

$ composer require icanhazstring/expressive-hashids-middleware

工作流程

中间件的主要目的是混淆外部世界对内部ID的访问。换句话说,您无需更改内部ID处理(如数据库中的自增)即可使用此中间件。

任何形式为/api/resource/{id}的传入请求都将使用此中间件进行解码。例如(默认配置)

/api/user/ABC(其中ABC是编码值)将生成如下请求属性

$attributes = $request->getAttributes();

/*
[
    'id' => 'ABC',
    '__hashids_identifier' => 1
]
*/

中间件不会覆盖属性!您可以使用HashidsMiddleware::ATTRIBUTE常量轻松访问此属性。

用法

使用expressive

在您的config/config.php中包含HashidsConfigProvider

$aggregator = new ConfigAggregator([
    ...
    \icanhazstring\Hashids\HashidsConfigProvider::class,
    ...
]);

确保在您的autoload文件之前包含HashidsConfigProvider

自定义配置

如果您想更改Hashids的参数,只需在您的autoload配置中提供HashidsConfigProvider::CONFIG_KEY并更改值到您所需。

return [
    \icanhazstring\Hashids\HashidsConfigProvider::CONFIG_KEY => [
        'salt'                 => '',
        'minHashLength'        => 0,
        'alphabet'             => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
        'resource_identifiert' => 'id'
    ]
];

使用策略

如果您想,您可以使用提供的策略来解码/编码对象中的数据。

要使用策略,请简单地使用提供的代理工厂HashidsHydratorDelegatorFactory并将其作为代理添加到您的hydrator中。

class ConfigProvider
{
    public function __invoke(): array
    {
        return [
            'hydrators' => [
                'delegators' => [
                    ArraySerializable::class => [
                        \icanhazstring\Hashids\Hydrator\HashidsHydratorDelegatorFactory:class
                    ]
                ]
            ],
        ];
    }
}