a Sensio Labs Product

The PHP micro-framework
based on the Symfony2 Components

Questions & Feedback

License

Creative Commons License Silex documentation is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

UrlGeneratorServiceProvider

The UrlGeneratorServiceProvider provides a service for generating URLs for named routes.

Parameters

None.

Services

  • url_generator: An instance of UrlGenerator, using the RouteCollection that is provided through the routes service. It has a generate method, which takes the route name as an argument, followed by an array of route parameters.

Registering

1
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());

Usage

The UrlGenerator provider provides a url_generator service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$app->get('/', function () {
    return 'welcome to the homepage';
})
->bind('homepage');

$app->get('/hello/{name}', function ($name) {
    return "Hello $name!";
})
->bind('hello');

$app->get('/navigation', function () use ($app) {
    return '<a href="'.$app['url_generator']->generate('homepage').'">Home</a>'.
           ' | '.
           '<a href="'.$app['url_generator']->generate('hello', array('name' => 'Igor')).'">Hello Igor</a>';
});

When using Twig, the service can be used like this:

1
{{ app.url_generator.generate('homepage') }}

Moreover, if you have twig-bridge in your composer.json, you will have access to the path() and url() functions:

1
2
3
4
{{ path('homepage') }}
{{ url('homepage') }} {# generates the absolute url http://example.org/ #}
{{ path('hello', {name: 'Fabien'}) }}
{{ url('hello', {name: 'Fabien'}) }} {# generates the absolute url http://example.org/hello/Fabien #}

Traits

Silex\Application\UrlGeneratorTrait adds the following shortcuts:

  • path: Generates a path.
  • url: Generates an absolute URL.
1
2
$app->path('homepage');
$app->url('homepage');
This website is powered by Silex and Twig. The Silex logo is © 2010,2011 Sensio Labs