roukmoute/hashids-bundle

将 hashids/hashids 集成到 Symfony 项目中

安装数量: 289,585

依赖者: 1

建议者: 0

安全: 0

星标: 45

关注者: 4

分支: 14

开放问题: 5

类型:symfony-bundle

v3.1.0 2021-12-09 14:23 UTC

README

SymfonyInsight Scrutinizer Code Quality Packagist Downloads

HashidsBundle

在 Symfony 项目中集成 hashids/hashids

使用 composer 安装

以下命令要求您全局安装了 Composer。
打开命令行,进入您的项目目录,并执行以下命令以下载此包的最新稳定版本

使用 Symfony Flex

    composer config extra.symfony.allow-contrib true
    composer req roukmoute/hashids-bundle

仅使用 Symfony 框架

    composer require roukmoute/hashids-bundle

如果此操作没有自动完成,请通过在您的项目的 config/bundles.php 文件中添加以下行来启用该包

<?php

return [
    …,
    Roukmoute\HashidsBundle\RoukmouteHashidsBundle::class => ['all' => true],
];

配置

配置 (config/packages/roukmoute_hashids.yaml) 如下所示

roukmoute_hashids:

    # if set, the hashids will differ from everyone else's
    salt:            ""

    # if set, will generate minimum length for the id
    # 0 — meaning hashes will be the shortest possible length
    min_hash_length: 0

    # if set, will use only characters of alphabet string
    alphabet:        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

    # if set to true, it will continue with the next available param converters
    passthrough:     false

    # if set to true, it tries to convert all arguments passed to the controller
    auto_convert:    false

用法

use Hashids\HashidsInterface;

public function postShow(HashidsInterface $hashids): Response
{
    $hashids->…
}

接下来与官方文档中相同。

Hashids 转换器

转换器名称: hashids.converter

hashids 转换器尝试将路由中设置的任何属性集转换为整数参数。

您可以使用 hashidid

/**
 * @Route("/users/{hashid}")
 */
public function getAction(int $user)
{
}

/**
 * @Route("/users/{id}")
 */
public function getAction(int $user)
{
}

您可以在同一 URL 中使用多个带有 _hash_ 前缀的 hashid。

/**
 * @Route("/users/{_hash_user}/status/{_hash_status}")
 */
public function getAction(int $user, int $status)
{
}

键必须与参数控制器中的键相同

/**
 *                          _hash_user _hash_status
 *                                 ↕            ↕
 * public function getAction(int $user, int $status)
 */

如果无法正确解码 hash,您将收到一个 LogicException

使用 auto_convert

auto_convert 尝试转换控制器中的所有参数。

roukmoute_hashids:
  auto_convert: true

基于上述示例

/**
 * @Route("/users/{user}/status/{status}")
 */
public function getAction(int $user, int $status)
{
}

如果激活了该功能,则从包中无法获取 LogicException 类型的异常。

使用 passthrough

passthrough 允许继续使用下一个可用的参数转换器。
因此,如果您想获取对象而不是整数,只需激活 passthrough

roukmoute_hashids:
    passthrough: true

基于上述示例

/**
 * @Route("/users/{hashid}")
 */
public function getAction(User $user)
{
}

如你所见,passthrough 功能允许使用 DoctrineParamConverter 或您创建的任何其他 ParamConverterInterface

Twig 扩展

用法

{{ path('users.show', {'hashid': user.id | hashids_encode }) }}
{{ app.request.query.get('hashid') | hashids_decode }}