跳到内容

安装

编辑此页

SonataAdminBundle 可以在项目生命周期的任何时刻安装。

下载扩展包

1
composer require sonata-project/admin-bundle

下载存储扩展包

您现在已经下载了 SonataAdminBundle。虽然此扩展包包含所有功能,但它需要存储扩展包才能与数据库通信。在使用 SonataAdminBundle 之前,您必须下载以下存储扩展包之一。官方存储扩展包是

您可以像下载 SonataAdminBundle 一样下载它们。请选择其中一个,并在继续之前按照其安装说明进行操作。

注意

不知道选择哪个?大多数新用户更喜欢 SonataDoctrineORMAdmin,以便与传统关系数据库(MySQL、PostgreSQL 等)交互。

启用扩展包

然后,通过在项目的 bundles.php 文件中添加以下行来启用扩展包及其依赖的扩展包

1
2
3
4
5
6
7
8
9
10
11
12
// config/bundles.php

return [
    // ...
    Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
    Sonata\BlockBundle\SonataBlockBundle::class => ['all' => true],
    Knp\Bundle\MenuBundle\KnpMenuBundle::class => ['all' => true],
    Sonata\AdminBundle\SonataAdminBundle::class => ['all' => true],
    Sonata\Doctrine\Bridge\Symfony\SonataDoctrineBundle::class => ['all' => true],
    Sonata\Form\Bridge\Symfony\SonataFormBundle::class => ['all' => true],
    Sonata\Twig\Bridge\Symfony\SonataTwigBundle::class => ['all' => true],
];

配置已安装的扩展包

现在所有需要的扩展包都已下载和注册,您必须添加一些配置。管理界面使用 SonataBlockBundle 将所有内容放在块中。您必须告诉 block bundle admin block 的存在。

1
2
3
4
5
6
7
# config/packages/sonata_admin.yaml

sonata_block:
    blocks:
        # enable the SonataAdminBundle block
        sonata.admin.block.admin_list:
            contexts: [admin]

注意

如果您现在还不完全理解什么是块,请不要太担心。SonataBlockBundle 是一个有用的工具,但为了使用 admin bundle,您不必理解它。

启用 "translator" 服务

SonataAdmin 需要 translator 服务来正确显示所有标签。更多信息: https://symfony.ac.cn/doc/5.4/translation.html#configuration

1
2
3
4
# config/packages/framework.yaml

framework:
    translator: { fallbacks: ['%locale%'] }

定义路由

现在扩展包已正确注册和配置。为了能够访问 SonataAdminBundle 的页面,Symfony 路由器需要知道 SonataAdminBundle 提供的路由。您可以通过将路由添加到应用程序的路由文件来做到这一点

1
2
3
4
5
6
7
8
9
10
# config/routes/sonata_admin.yaml

admin_area:
    resource: '@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
    prefix: /admin

_sonata_admin:
    resource: .
    type: sonata_admin
    prefix: /admin

注意

如果您使用 XML 或 PHP 来指定应用程序的配置,则上述路由配置必须根据您的格式(即 XML 或 PHP)放置在 routing.xml 或 routing.php 中。

注意

对于那些对 resource: . 设置感到好奇的人:这是一种不寻常的语法,但使用它的原因是 Symfony 要求定义一个资源(指向真实文件)。一旦此验证通过,Sonata 的 AdminPoolLoader 将负责处理此路由,并且它会忽略 resource 设置。

此时,您已经可以通过访问 URL: http://yoursite.local/admin/dashboard 访问(空)管理仪表板。

准备您的环境

与您安装的所有扩展包一样,清除缓存并安装 assets 是一个好习惯

1
2
bin/console cache:clear
bin/console assets:install

管理界面

您已完成安装过程,恭喜。如果您启动服务器,您现在可以访问 https://127.0.0.1:8000/admin 上的管理页面

注意

本教程假定您正在使用内置服务器,使用 bin/console server:start(或 server:run)命令。

Sonata Dashboard

如您所见,管理面板非常空。这是因为还没有扩展包为 admin bundle 提供管理功能。幸运的是,您将在 下一章 学习如何做到这一点。

本作品(包括代码示例)根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本