简体   繁体   中英

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.

For that aim, I've created a Listener event as follow:

<?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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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