跳到内容

SensioFrameworkExtraBundle

编辑此页
不再建议在当前的 Symfony 应用程序中使用此扩展包。此扩展包提供的所有注解现在都内置在 Symfony 中作为 PHP 属性。查看 Symfony 属性的完整列表

默认的 Symfony FrameworkBundle 实现了基本但健壮且灵活的 MVC 框架。SensioFrameworkExtraBundle 扩展了它,添加了便捷的约定和注解。它允许更简洁的控制器。

安装

此扩展包有一个官方的 Symfony 配方。要自动安装和配置它,请运行

1
$ composer require sensio/framework-extra-bundle

完成!

配置

当扩展包在您的 Kernel 类中注册时,默认情况下会启用该扩展包提供的所有功能。

默认配置如下

1
2
3
4
5
6
sensio_framework_extra:
    router:      { annotations: true } # Deprecated; use routing annotations of Symfony core instead
    request:     { converters: true, auto_convert: true }
    view:        { annotations: true }
    cache:       { annotations: true }
    security:    { annotations: true }

您可以通过将一个或多个设置定义为 false 来禁用某些注解和约定。

控制器的注解

注解是轻松配置控制器的绝佳方式,从路由到缓存配置。

即使注解不是 PHP 的原生功能,但与经典的 Symfony 配置方法相比,它仍然有几个优点

  • 代码和配置位于同一位置(控制器类中);
  • 简单易学易用;
  • 编写简洁;
  • 使您的控制器变得精简(因为其唯一职责是从模型中获取数据)。

提示

如果您使用视图类,注解是避免为简单和常见用例创建视图类的好方法。

以下注解由扩展包定义

此示例展示了所有可用的注解的实际应用(此处和所有其他示例中,都显示了普通的旧注解和 PHP 8 属性)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

/**
 * @Route("/blog")
 * @Cache(expires="tomorrow")
 */
class AnnotController
{
    /**
     * @Route("/")
     * @Template
     */
    public function index()
    {
        $posts = ...;

        return array('posts' => $posts);
    }

    /**
     * @Route("/{id}")
     * @Method("GET")
     * @ParamConverter("post", class="SensioBlogBundle:Post")
     * @Template("@SensioBlog/annot/show.html.twig", vars={"post"})
     * @Cache(smaxage="15", lastmodified="post.getUpdatedAt()", etag="'Post' ~ post.getId() ~ post.getUpdatedAt()")
     * @IsGranted("ROLE_SPECIAL_USER")
     * @Security("is_granted('ROLE_ADMIN') and is_granted('POST_SHOW', post)")
     */
    public function show(Post $post)
    {
    }
}

由于 showAction 方法遵循某些约定,因此您可以省略某些注解

1
2
3
4
5
6
7
8
9
/**
 * @Route("/{id}")
 * @Cache(smaxage="15", lastModified="post.getUpdatedAt()", Etag="'Post' ~ post.getId() ~ post.getUpdatedAt()")
 * @IsGranted("ROLE_SPECIAL_USER")
 * @Security("is_granted('ROLE_ADMIN') and is_granted('POST_SHOW', post)")
 */
public function show(Post $post)
{
}

路由需要像任何其他路由资源一样导入才能激活,例如

1
2
3
4
5
6
# config/routes/annotations.yaml

# import routes from a controller directory
annot:
    resource: "@AnnotRoutingBundle/Controller"
    type:     annotation
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本