如何区分 Symfony 控制器中的 Action 或 Method

How to differentiate Action or Method in Symfony's controller

当我必须在 Symfony 控制器 中创建方法时,我按照惯例在控制器的所有方法中添加后缀 Action

但是我想问一下,规则Action后缀是什么?

如果函数没有return任何布局响应仍然是Action?

示例:

// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class BlogController extends Controller
{
  public function showAction($slug)
  {
      // ...
      return $this->render("foo.html.twig")
  }

  public function eraseElement($element)
  {
      // ...
      return true;
  }
}

在 symfony 最佳实践中,您可以阅读以下内容:

The first Symfony versions required that controller method names ended in Action (e.g. newAction(), showAction()). This suffix became optional when annotations were introduced for controllers. In modern Symfony applications this suffix is neither required nor recommended, so you can safely remove it.

在现代 Symfony 应用程序中,使用注释是最佳实践:

In addition, using annotations for routing, caching and security simplifies configuration. You don't need to browse tens of files created with different formats (YAML, XML, PHP): all the configuration is just where you need it and it only uses one format.

the link

从技术上讲,它一个动作。它是一种绑定到某些 URI 模式的操作,并且在您尝试加载该 URI 时被调用。但同时它是一个无效控制器,因为symfony控制器必须 return一个响应。如果他们不这样做,您将遇到这样的错误:

Error: The controller must return a response (true given).

Action 后缀怎么样 - 如果您使用 YAML 路由和 b:c:m 格式,这是必不可少的,因为否则该方法根本不会被识别为操作。如果您使用 Annotations 路由,您可能有一个没有后缀的方法,但添加 "Action" 仍然是最佳实践,即使它不是必需的。

有关详细信息,请阅读以下链接: