Create your first route | Symfony 2 | Beginners guide

Hey Symfony 2 lovers,

Let’s have a good understanding about routings in Symfony 2. Routing is the navigational paths (directives) in your application. For instance if you want to show all your products in your shopping cart application, which was developed by Symfony 2, routing could be either ‘your_cart/web/app_dev.php/show_all_items’ or ‘your_cart/web/app.php/show_all_items’. In here ‘your_cart‘ is the name of your application, ‘web‘ is the default path in Symfony 2 (you can hide this later), ‘app_dev.php‘ and ‘app.php‘ are two environments in the same application, such as development and production environment. These environments are there to distinguish your application in different purposes which I am not going to discuss any further. Our main concern in here is the ‘show_all_items‘ bit. This is a routing which fires a function in a controller. If you are new to a frameworks this concept might be little surprising to you. This is how the major frameworks work. When you hit a path, such as ‘show_users‘ will call a predefined function in a predefined controller. If you see something like this ‘show_users/10‘, probably that is to show how the user which has the id of 10, something like that. This 10, will be passed to a method as a parameter, such as ‘public function showUser($id)’.

Let’s create a basic route in Symfony 2 to understand this routing concept. Let’s recall our HelloBundle which we created in our first post.

  • Navigate and open the ‘routing.yml’ file in src/Test/HelloBundle/Resources/config’.

 

symfony 2 routing

     
  • You will find there is a routing already called ‘test_hello_homepage’. If you wonder how it is there, it was created by Symfony 2 when you generate the bundle via console. Let’s create new routing for a path ‘routing_test’. In your application, when somebody reaches ‘web/app_dev.php/routing_test’ , it should call a separate function. So let’s create that routing and give it an unique alias called ‘test_routing’. This alias can be anything, but needs to be an unique alias, that’s the important factor you should remember in here. When someone reaches that url, we need to call a function in ‘DefaultController.php’ file (You can point to any other controller than DefaultController.php. To do that you need to point to that controller, instead of the term ‘Default’, which is the controller, in the routing below). Let’s give the name of the function as ‘public function testRouting()’. In the Symfony 2 naming conventions we need to remember one thing, which is functions needs to be suffixed with the term ‘Action’. So the above function name will be ‘testRoutingAction()’ instead of ‘testRouting()’.(Tip : When creating the routing, you can mention the route in any routing.yml file, but for better understanding and durability, we are adding the route under it’s bundle). Ok, we are all set and so let’s create the routing first. Add this code at the top/bottom of the above opened ‘routing.yml’ file.
       
    test_routing:
        pattern:  /routing_test/
        defaults: { _controller: TestHelloBundle:Default:testRouting }

     

    So, the file looks like this now,

    symfony 2 routing

 

  • Now, Symfony 2 knows where to call the function when someone hit that path. Have we created the function in DefaultController.php ? No, we haven’t. So let’s go and create it. Add following function in your ‘DefaultController.php‘ under ‘src/Test/HelloBundle/Controller‘.
       
    public function testRoutingAction()
        {
            return $this->render(‘TestHelloBundle:Default:index.html.twig’, array(‘name’ => ‘Your name’));
        }

    Now your DefaultController.php looks like this,

    symfony 2 routing

 

  • That’s is. We are there now, try calling your application in the browser by giving this URL (make sure you save all your work 😉 ) ‘http://localhost/your_project/web/app_dev.php/routing_test/’. This should give you a page something like this. See below,

 

symfony 2 routing

  • See, your code is working Yay!!. Well that’ a pretty simple one. For the ones who are wondering what the heck this line does ‘return $this->render(‘TestHelloBundle:Default:index.html.twig’, array(‘name’ => ‘Your name’)); ‘, this line just pass one argument called ‘name’ to the Symfony 2 view file, which is a Twig file called ‘index.html.twig’ inside ‘src/Test/HelloBundle/Resources/views/default’ path. This is the output view file which is being called by the controller function, which is ‘testRoutingAction()’.
    1.  
  • Instead of printing, ‘Hello Your name!’ let’s actually print your name. To do that, we will be passing the name in URL, in following format ‘your_project/web/app_dev.php/routing_test/David’. Now the URL is slightly different with addition of a name string. Now our job is to alter our routing file and controller like this. Open up your routing.yml file again and add this little tweak, ‘{name}’ after the routing (excluding quotations), see below,

 

symfony 2 routing

  • Also change your testRoutingAction() in the controller to accept one parameter, which is $name, so that would be ‘testRoutingAction($name)’. Remember name of variable $name should match the parameter we added in the above routing.yaml file. Now, add this bit in the controller and pass this $name variable instead of hard coded text in to the view file to render. See below,

 

symfony 2 routing

  • That’s it, now you can call the URL by passing your name ‘http://localhost/your_project/web/app_dev.php/routing_test/David’. See the output below,

 

symfony 2 routing

That’s pretty much it for today. Hope you enjoyed my post. Feel free to place your comments in the section below. Cheers! 🙂

Share

7 thoughts on “Create your first route | Symfony 2 | Beginners guide

  1. Just wish to say your article is as surprising. The clarity in your post is just spectacular
    and i could assume you’re an expert on this subject.
    Well with your permission let me to grab your feed to keep updated with forthcoming post.
    Thanks a million and please carry on the gratifying work.

    • Anjana Silva says:

      Thank you very much Robt. Appreciate your motivational feedback. Sure I will keep on publishing articles on Symfony 2. Please make sure you have subscribed to my newsletter to get updates directly into your inbox. The subscription box is in top of the right column of the website. Thanks once again 🙂

    • Dear Zhao,I am a Ph.D. candidate in computer science, and will graduate at the end this year. Now I’m confused that what kind of job should I select. To be a university teacher or find a job at company? Can you give me some advice? I want to know why you select this job. In my opinion, you are fit to be a university teacher.With best regards.figo

Leave a Reply to SAYURU SAMARASINGHE Cancel reply

Your email address will not be published. Required fields are marked *