Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a friendly URL in Symfony PHP?

I always tend to forget these built-in Symfony functions for making links.

like image 254
andyuk Avatar asked Aug 29 '08 14:08

andyuk


People also ask

How can I get SEO friendly URL in PHP?

Create SEO Friendly URL in PHPThe generateSeoURL() function automatically creates SEO friendly URL slug from the string using PHP. A title string needs to be passed as input and it returns a human-friendly URL string with a hyphen ( - ) as the word separator. $string – Required.

What is a route in Symfony?

The routing configuration defines which action to run for each incoming URL. It also provides other useful features, like generating SEO-friendly URLs (e.g. /read/intro-to-symfony instead of index.


1 Answers

If your goal is to have user-friendly URLs throughout your application, use the following approach:

1) Create a routing rule for your module/action in the application's routing.yml file. The following example is a routing rule for an action that shows the most recent questions in an application, defaulting to page 1 (using a pager):

recent_questions:
   url:    questions/recent/:page
   param:  { module: questions, action: recent, page: 1 }

2) Once the routing rule is set, use the url_for() helper in your template to format outgoing URLs.

<a href="<?php echo url_for('questions/recent?page=1') ?>">Recent Questions</a>

In this example, the following URL will be constructed: http://myapp/questions/recent/1.html.

3) Incoming URLs (requests) will be analyzed by the routing system, and if a pattern match is found in the routing rule configuration, the named wildcards (ie. the :/page portion of the URL) will become request parameters.

You can also use the link_to() helper to output a URL without using the HTML <a> tag.

like image 51
jamz Avatar answered Sep 19 '22 12:09

jamz