21.10.2015 Views

1-33

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Symfony2 – Franz Jordán 2011<br />

To generate a URL, you need to specify the name of the route (e.g. blog_show) and any<br />

wildcards (e.g. slug = my-blog-post) used in the pattern for that route. With this<br />

information, any URL can easily be generated:<br />

class MainController extends Controller<br />

{<br />

public function showAction($slug)<br />

{<br />

// ...<br />

}<br />

}<br />

$url = $this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));<br />

In an upcoming section, you'll learn how to generate URLs from inside templates.<br />

Generating Absolute URLs<br />

By default, the router will generate relative URLs (e.g. /blog). To generate an absolute URL,<br />

simply pass true to the third argument of the generate() method:<br />

$router->generate('blog_show', array('slug' => 'my-blog-post'), true);<br />

// http://www.example.com/blog/my-blog-post<br />

The host that's used when generating an absolute URL is the host of the currentRequest object.<br />

This is detected automatically based on server information supplied by PHP. When generating<br />

absolute URLs for scripts run from the command line, you'll need to manually set the desired<br />

host on the Request object:<br />

$request->headers->set('HOST', 'www.example.com');<br />

Generating URLs with Query Strings<br />

The generate method takes an array of wildcard values to generate the URI. But if you pass<br />

extra ones, they will be added to the URI as a query string:<br />

$router->generate('blog', array('page' => 2, 'category' => 'Symfony'));<br />

// /blog/2?category=Symfony<br />

Generating URLs from a template<br />

The most common place to generate a URL is from within a template when linking between<br />

pages in your application. This is done just as before, but using a template helper function:<br />

<br />

Read this blog post.<br />

<br />

Absolute URLs can also be generated.<br />

<br />

Read this blog post.<br />

<br />

65

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!