【问题标题】:Creating a custom requirement validator for @Route annotation in Symfony在 Symfony 中为 @Route 注解创建自定义需求验证器
【发布时间】:2016-01-27 15:59:56
【问题描述】:

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

我已经看到很多类似的问题和教程来创建自定义注释,但不是这样的问题。

当前

/**
 * @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;
     }
}

【问题讨论】:

    标签: symfony


    【解决方案1】:

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

    <?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)
    

    【讨论】:

    • 我不清楚。你能举个例子吗?谢谢
    • 好的,我只是仔细阅读了您的代码,一切正常,只需删除静态调用周围的 "" 引号,如下所示 "id"=MyClass::MyValidation 并将 use Namespace\MyClass 放在命名空间使用部分
    • 我刚刚提出了可能的解决方案,以解释我的问题到底是什么意思,所以如果必须实施您刚刚建议的内容,我会收到AnnotationException 错误。
    • 我在手机上,我回家后会检查 ~ 30 分钟
    • 我更新了我的答案,请您检查并提供您的 symfony 版本吗?
    【解决方案2】:

    我建议改用@ParamConverter 注释。在这种情况下,您不需要验证。欲了解更多信息ParamConverter

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
    
    /**
     * @Route("/blog/{id}")
     * @ParamConverter("post", class="SensioBlogBundle:Post")
     */
    public function showAction(Post $post)
    {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 2011-03-25
      • 1970-01-01
      • 2018-10-25
      相关资源
      最近更新 更多