简体   繁体   English

Symfony controller 对uuid有要求的路由

[英]Symfony controller route with requirements on uuid

I have an entity like this:我有一个这样的实体:

class Building
{
    /**
     * @var int
     *
     * @ORM\Column(name="id")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     * @Expose()
     */
    private $id;

    ....
}

I would like to know if there is a way to specify the requirements on uuid to separate two different url like this on rest API:我想知道是否有一种方法可以在 rest API 上指定对 uuid 的要求来分隔两个不同的 url 像这样:

class BuildingController extends BaseController
{   
    /**
     *
     * @Rest\Get("/buildings/{id}", requirements={"id" = "\d+"})
     */
    public function getBuildingAction($id)
    {
        //code
    }

\d+ is correct for integer value but I would like to change It to uuid type because I have another route for example this: \d+对于 integer 值是正确的,但我想将其更改为 uuid 类型,因为我有另一条路线,例如:

 /**
 * @Rest\Get("/buildings/lot")
 */
public function getBuildingLotAction(Request $request)
{
    //code
}

Is possible to define uuid on requirements type?可以在需求类型上定义 uuid 吗?

Thanks谢谢

I believe you can simply put "/buildings/lot" action before /buildings/{id}. 我相信你可以简单地在/ buildings / {id}之前添加“/ buildings / lot”动作。

First route always win. 第一条路线总是赢。

Best I could find - this article gives example of regexp, so I guess PHP regexps should work fine. 我能找到的最好 - 这篇文章给出了regexp的例子,所以我想PHP regexp应该可以正常工作。

There is also mention of Symfony expression language , though without example for annotations. 提到了Symfony表达式语言 ,但没有注释的例子。

I have used like this.我用过这样的。 it was worked for me!它对我有用!

/**
    *  @Rest\Patch("stocks/{stock}", requirements={"stock" = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"})
    */

There is other regex structures have give 还有其他正则表达式结构

@ORM\GeneratedValue(strategy="UUID") uses UUID V1 and thus you need to use this expression: @ORM\GeneratedValue(strategy="UUID")使用 UUID V1,因此您需要使用此表达式:

/**
 *
 * @Rest\Get("/buildings/{id}", requirements={"id" = "[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"})
 */
public function getBuildingAction($id)
{
    //code
}

If you want to catch any version of UUID you can use this "[0-9a-f]{8}-[0-9a-f]{4}-[1-6][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"如果您想捕获任何版本的 UUID,您可以使用此"[0-9a-f]{8}-[0-9a-f]{4}-[1-6][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"

As of Symfony 6.1, we can use predefined route requirements as explained in 0x6d6c comment:从 Symfony 6.1 开始,我们可以使用预定义路由要求,如 0x6d6c 注释中所述:

use Symfony\Component\Routing\Requirement\Requirement;

#[Route('/products/{id}',
    name: 'product_show',
    requirements: ['id' => Requirement::UUID_V6]
)]
public function show(string $id): Response

Check the feature introduction on the Symfony blog .查看Symfony博客上的功能介绍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM