ok you can get current route name with app.request.attributes.get('_route')
but it's not possible to get from an url ?
Something like app.request.attributes.get('/about')
?
Creating Routes in YAML, XML or PHP Files Instead of defining routes in the controller classes, you can define them in a separate YAML, XML or PHP file.
As you might know, Symfony2 uses annotations for Doctrine mapping information and validation configuration. Of course, it is entirely optional, and the same can be done with XML, YAML, or even PHP. But using annotations is convenient and allows you to define everything in the same file.
Symfony provides a Routing component which allows us, for a HTTP request/URL, to execute a specific function (also known as "Controller"). Note: Controllers must be a callable, for example: an anonymous function: $controller = function (Request $request) { return new Response() }; .
You can use the Router
class/service for this:
public function indexAction()
{
$router = $this->get('router');
$route = $router->match('/foo')['_route'];
}
More information in the documentation
I recently discovered that the match() method uses the HTTP METHOD of the current request in order to match the request. So if you are doing a PUT request for example, it will try to match the URL you have given with a PUT method, resulting in a MethodNotAllowedException exception (for example, getting the referer).
To avoid this I'm using this workaround:
// set context with GET method of the previous ajax call
$context = $this->get('router')->getContext();
$currentMethod = $context->getMethod();
$context->setMethod('GET');
// match route
$routeParams = $this->get('router')->match($routePath);
// set back original http method
$context->setMethod($currentMethod);
However it may not be true that it's always a GET request. It could be a POST request in your case.
I've sent this problem to the Symfony community. Let's see what they propose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With