It is time to see how the router works in Silex. We would like to add a simple
endpoint for the home page. As we already mentioned, the
$app
instance can manage almost
anything, including routes. Add the following code at the end of
the public/index.php
file:
$app->get('/', function(Application $app) { return $app['twig']->render('home.twig'); });
This is a similar way of adding routes to the
one that Laravel follows. We invoked the get
method as it is a GET endpoint, and we passed
the route string and the Application
instance. As we mentioned here, $app
also acts as a dependency injector—in fact, it extends from one:
Pimple—so you will notice the Application
instance almost everywhere. The result
of the anonymous function will be the response that we will send to
the user—in this case, a rendered Twig template.
Right now, this will not do the trick. In order
to let Silex know that you are done setting up your application,
you need to invoke the run
method at the
very end of the public/index.php
file.
Remember that if you need to add anything else to this file, it has
to be before this line:
$app->run();
You have already worked with Twig, so we will
not spend too much time on this. The first thing to add is the
views/home.twig
template:
{% extends "layout.twig" %} {% block content %} <h1>Hi visitor!</h1> {% endblock %}
Now, as you might have already guessed, we will
add the views/layout.twig
template, as
follows:
<html> <head> <title>Silex Example</title> </head> <body> {% block content %} {% endblock %} </body> </html>
Try accessing the home page of your application; you should get the following result:
