Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route name for url generation when using annotations in Symfony 2

Tags:

php

symfony

Let's say I have an action:

/**
 * @Route("/current")
 *
 * @return Response
 */
public function currentAction() 
{
}

And now I need to generate url to this action. $this->generateUrl() controller's method accepts route name as an argument. Obviously I have no such name as long as I use annotations.

Any workarounds for this?

like image 431
zerkms Avatar asked Jan 30 '12 03:01

zerkms


People also ask

What is route in Symfony?

The routing configuration defines which action to run for each incoming URL. It also provides other useful features, like generating SEO-friendly URLs (e.g. /read/intro-to-symfony instead of index.php?article_id=57 ).

How does Symfony routing work?

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() }; .

What is a rout in PHP?

The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.

What are annotations Symfony?

annotations are literally configuration inside PHP comments. If you don't like them, you can always use YAML or XML instead: Symfony is super flexible.


1 Answers

Got it:

/**
 * @Route("/current", name="foobar")
 *
 * @return Response
 */
public function currentAction() 
{
}

Found it by reading sources, but actually it is explained in documentation as well: http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/routing.html#route-name

As @Mihai Stancu mentioned - there is always a default name:

A route defined with the @Route annotation is given a default name composed of the bundle name, the controller name and the action name.

in this case it will be a bundlename_controllername_current

like image 120
zerkms Avatar answered Sep 26 '22 11:09

zerkms