Symfony Routing - Libbna/CUSTOM-CMS GitHub Wiki
Symfony - Routing
- Routing maps request URI to a specific controller's method.
- Generally, routing checks the page segment against a set of constraints. If any constraint matches, then it returns a set of values. One of the main value is the controller.
Symfony Installation
- Follow the steps mentioned in this reference site - Symfony Installation
Annotations
- Annotation simplifies the configuration by declaring the configuration in the coding itself.
- Annotation is nothing but providing meta information about class, methods, and properties.
- Routing uses annotation extensively. Even though routing can be done without annotation, annotation simplifies routing to a large extent.
- Following is a sample annotation :
/**
* @Route(“/student/home”)
*/
public function homeAction() {
// ...
}
Routing Concepts
- Consider the StudentController class.
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class StudentController extends Controller {
/**
* @Route(“/student/home”)
*/
public function homeAction() {
// ...
}
/**
* @Route(“/student/about”)
*/
public function aboutAction() {
}
}
- Here, the routing performs two steps.
- If you go to /student/home, the first route is matched then homeAction() is executed.
- Otherwise, If you go to /student/about, the second route is matched and then aboutAction() is executed.
Passing parameters to routes
- Consider the following example :
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class TestController extends Controller{
// Demo route with parameters
/**
* @Route("/contact/{name}")
*/
public function contactNameAction(string $name){
return new Response("Name is : " . $name);
}
}
- Here, if you go to /student/contact/Tom, the name "Tom" is the paramter passed via the route, so the first route is matched wherein "{name}" catches the incoming parameter then contactNameAction() is executed, which displays the name as a response.
@TODO: add references to examples which shows how to create a new route.