I'm developing my first decent-sized PHP site, and I'm a bit confused about what the "right way" (assuming there ever is such a thing) to handle clean/friendly/pretty URLs in the application.
The way I see it, there are two main options (I'll use a simplified social news site as an example):
1. Use mod_rewrite to handle all potential URLs. This would look similar, but not identical, to the following:
RewriteRule ^article/?([^/]*)/?([^/]*)/?([^/]*) /content/articles.php?articleid=$1&slug=$2
RewriteRule ^users/?([^/]*)/?([^/]*) /content/users.php?userid=$1&username=$2
RewriteRule ^search/?([^/]*)/? /content/search.php?query=$1
2. Pass everything to some handler script and let it worry about the details:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) handler.php?content=$1
Clearly this is all untested "air code," but you get the point.
Option 1 (.htaccess and several .php files) was often used "in the past" ; now, I see option 2 (every request going through one .php file) used a lot more.
The main advantages I see with option 2 are :
index.php
: if you need some code executed for all requests, put it there, and you're sure it'll always be executed.
A couple of years ago, I would have gone with option 1 ; now that I use MVC and Frameworks, I always go with option 2.
Really this is the "are frameworks worth using?" question in disguise.
Using mod_rewrite to define your URL routes is quick and easy (if you understand regular expressions...) but your application code is oblivious to the URLs unless you duplicate the information somewhere.
Usually, people duplicate this information many times without thinking about it, by hard-coding URLs in the links in their views, or in redirects. This is really messy, and will one day cause pain when you decide to change the URL structure of your site halfway through development. You're bound to miss one and end up with a 404 somewhere.
Using a routing component in your application (such as the one in Symfony) means you can attach names to your routes, allowing you to define your URLs once and re-use them many times:
# apps/frontend/config/routing.yml
homepage:
url: /
param: { module: default, action: index }
This makes it really easy to link to pages of your site without repeating yourself:
<?php echo url_for('@homepage') ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With