13/05/2015 - SYMFONY, TWIG
This post shows you how to use annotations to handle routes instead of commonly used yml files. See more information about @route and @method. Also, see how routing works.
Assuming that we have two bundles as: Football\FrontendBundle
and Football\BackendBundle
.
Every URI for backend bundle will automatically start with "/backend" prefix.
# sport/app/config/routing.yml
football_frontend:
resource: "@FootballFrontendBundle/Controller"
prefix: /
type: annotation
football_backend:
resource: "@FootballBackendBundle/Controller"
prefix: /backend
type: annotation
When we don't use "name" parameter in @Route annotation to assign a specific name to the route, it will automatically generate one so for example, the route name for helloAction
would be football_frontend_hello
.
namespace Football\FrontendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/**
* @Route("")
*/
class DefaultController extends Controller
{
/**
* @Route("")
* @Method({"GET"})
*/
public function indexAction()
{
// ...
}
}
namespace Football\FrontendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/**
* @Route("/country")
*/
class CountryController extends Controller
{
/**
* @Route("")
* @Method({"GET"})
*/
public function indexAction()
{
// ...
}
/**
* @Route("")
* @Method({"POST"})
*/
public function createAction()
{
// ...
}
/**
* @Route("{id}", requirements={"id" = "\d+"})
* @Method({"GET"})
*/
public function deleteAction($id)
{
// ...
}
}
namespace Football\BackendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/**
* @Route("")
*/
class DefaultController extends Controller
{
/**
* @Route("")
* @Method({"GET"})
*/
public function indexAction()
{
// ...
}
}
If there are two or more identical routers then the first one always wins so if you meant to call second one unfortunately first one will be called.
inanzzz-MBP:sport inanzzz$ php app/console router:debug
[router] Current routes
Name Method Scheme Host Path
...
...
football_frontend_country_index GET ANY ANY /country
football_frontend_country_create POST ANY ANY /country
football_frontend_country_delete GET ANY ANY /country{id}
football_frontend_default_index GET ANY ANY /
football_backend_default_index GET ANY ANY /backend/