我正在从Symfony 3.3升级到Symfony 4。
KNPMenu在Symfony 3.3下运行正常,但现在我看到了这个例外:
在渲染模板期间抛出异常(" The 菜单"主要"未定义。")。
services.yaml
App\Menu\MenuBuilder:
public: true
tags:
- { name: app.menu_builder.admin, method: createAdminMenu, alias: admin }
- { name: app.menu_builder.calendar, method: createCalendarMenu, alias: calendar }
- { name: app.menu_builder.main, method: createMainMenu, alias: main }
- { name: app.menu_builder.trailer, method: createTrailerMenu, alias: trailer }
- { name: app.menu_builder.user, method: createUserMenu, alias: user }
使用MenuBuilder
Namespace App\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\Security\Core\Security;
class MenuBuilder implements ContainerAwareInterface
{
use ContainerAwareTrait;
private $factory;
/**
* @param FactoryInterface $factory
*/
public function __construct( FactoryInterface $factory )
{
$this->factory = $factory;
}
我在 __ construct 中加了一个die('here');
,它永远不会被执行。
使用 php bin / console debug:容器菜单产生:
Information for Service "App\Menu\MenuBuilder"
==============================================
---------------- -------------------------------------------------------------------------
Option Value
---------------- -------------------------------------------------------------------------
Service ID App\Menu\MenuBuilder
Class App\Menu\MenuBuilder
Tags app.menu_builder.admin (method: createAdminMenu, alias: admin)
app.menu_builder.calendar (method: createCalendarMenu, alias: calendar)
app.menu_builder.main (method: createMainMenu, alias: main)
app.menu_builder.trailer (method: createTrailerMenu, alias: trailer)
app.menu_builder.user (method: createUserMenu, alias: user)
Public yes
Synthetic no
Lazy no
Shared yes
Abstract no
Autowired yes
Autoconfigured yes
---------------- -------------------------------------------------------------------------
如何让MenuBuilder __construct执行?
答案 0 :(得分:1)
谢谢大家的时间。
这个要点非常有用:https://gist.github.com/lsv/4d8044d21819f28f0dde52a3fb8211a0
这个答案很有帮助:How to avoid "knp_menu.factory" deprecation?
<强> services.yaml 强>
app.menu_builder:
class: App\Menu\MenuBuilder
app.menu.main:
class: Knp\Menu\MenuItem
factory: ['@app.menu_builder', 'createMainMenu']
arguments: { $options: [] }
tags:
- { name: knp_menu.menu, alias: main }
我使用php bin/console debug:autowiring security
获取安全授权检查程序
然后我更新了 MenuBuilder.php :
Namespace App\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class MenuBuilder
{
private $factory;
private $security;
/**
* @param FactoryInterface $factory
*/
public function __construct( FactoryInterface $factory, AuthorizationCheckerInterface $security )
{
$this->factory = $factory;
$this->security = $security;
}
添加SecurityAuthorizationChecker允许我控制使用此语句提供的菜单项:
if( $this->security->isGranted( 'IS_AUTHENTICATED_FULLY' ) )