简体   繁体   English

Symfony2:如何获取路由前缀

[英]Symfony2: How to get the route prefix

What I wonder to do is that I have an admin panel which I can access with 'admin' prefix but it's accessible only if you go toward the configuration page first. 我想知道的是,我有一个管理面板,可以使用“ admin”前缀访问,但只有先进入配置页面后才能访问。

For that aim, I've created a Listener event as follow: 为此,我创建了一个Listener事件,如下所示:

<?php

namespace Config\ConfigBundle\Listener;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class ConfigListener {

public function __construct(ContainerInterface $container){

    $this->router = $container->get('router');
    $this->em = $container->get('doctrine')->getEntityManager();;

}

public function onKernelRequest(GetResponseEvent $event)
{
    $route = $event->getRequest()->attributes->get('_route');
    if ( $route == 'admin') {

        $config = $this->em->getRepository('ConfigBundle:Config')->findConfig();
        if($config == null){
            $event->setResponse(new RedirectResponse($this->router->generate('adminConfig')));
        }   
    } 
}

}

This code works fine, but, it only get the route named 'admin', and what I want is to check the prefix of this route if it's equal to 'admin' to redirect toward the config page. 这段代码可以正常工作,但是,它只能获取名为“ admin”的路由,而我想要的是检查此路由的前缀(如果它等于“ admin”,以重定向到配置页面)。

I am missing somthing, and I don't know how to resolve that issue... 我缺少任何东西,我不知道该如何解决...

You can check if route contains 'admin' prefix using following snippet: 您可以使用以下代码段检查路由是否包含“ admin”前缀:

if (0 == strpos($route, 'admin')) {
    // perform redirect
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM