在 Symfony 中为 @Route 注释创建自定义需求验证器 [英] Creating a custom requirement validator for @Route annotation in Symfony

查看:27
本文介绍了在 Symfony 中为 @Route 注释创建自定义需求验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下所示,我的 @Route->requirements 下面的正则表达式(我在许多其他控制器/方法中使用它)有点长,看起来不太好并且 <强>最重要的是 在未来语法更新的情况下可能很难维护所以问题是,我们可以做如下的事情吗?

As you can see below, my @Route->requirements regex below (I'm using it in many other controller/methods) is a bit long, doesn't look good and most importantly it could be hard to maintain in the case of syntax update in future so the question is, are we able to do something like below?

我看过很多类似的问题和教程来创建自定义注释,但不是这个问题.

I've seen many similar questions and tutorials for creating custom annotations but not something like this question.

当前

/**
 * @param string $id
 *
 * @Method({"GET"})
 * @Route("/class/{id}", requirements={"id"="([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}"})
 * @Secure(roles="ROLE_ADMIN")
 *
 * @return Response
 */
public function getClassAction($id)

可能是这样的

/**
 * @param string $id
 *
 * @Method({"GET"})
 * @Route("/class/{id}", requirements={"id"="MyClass::MyValidation"})
 * @Secure(roles="ROLE_ADMIN")
 *
 * @return Response
 */
public function getClassAction($id)

我的课堂

MyClass
{
     // Would be ideal to stick this into parameters.yml though
     const ID = "([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}";

     public function MyValidation($value)
     {
          if (!preg_match(self::ID, $value)) {
               return 'Bad ID';
          }

          return true;
     }
}

推荐答案

你应该直接使用模式如下:

You should just use the pattern directly as follow :

<?php

use X\Y\Z\MyClass;

class XYZ
{

/**
 * @param string $id
 *
 * @Method({"GET"})
 * @Route("/class/{id}", requirements={"id":MyClass::ID})
 * @Secure(roles="ROLE_ADMIN")
 *
 * @return Response
 */
public function getClassAction($id)

这篇关于在 Symfony 中为 @Route 注释创建自定义需求验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆