I’m doing my first single-entry site and based on the result, I can’t see the benefit.
I’ve implemented the following:
- .htaccess redirects all requests to index.php at the root
- Url is parsed and each /segment/ is stored as an element in an array
- First segment indicates which folder to include (e.g. “users” » “/pages/users/index.php”).
- index.php file of each folder parses the remaining elements in the segments array until array is empty.
- content.php file of each folder is included if there are no more elements in the segments array, indicating that the destination file is reached
Sample
File structure ( folders in [] ):
- [root]
- index.php
- [pages]
- [users]
- index.php
- content.php
- [profile]
- index.php
- content.php
- [edit]
- index.php
- content.php
- [other-page]
- index.php
- content.php
- [users]
Request: http://mysite.com/users/profile/
-
.htaccess redirects request to http://mysite.com/index.php
-
URL is parsed and segments array contains: [1] users, [2] profile
-
index.php maps [1] to “pages/users/index.php”, so includes that file
-
pages/users/index.php maps [2] to pages/users/profile/index.php, so includes that file
-
Since no other elements in the segments array, the contents.php file in the current folder (pages/users/profile) is included.
I’m not really seeing the benefit of doing this over having functions that include components of the site (e.g. include_header(), include_footer(), etc.), so I conclude that I’m doing something terribly wrong. I’m just not sure what it is.
This version you have is lacking some functions and only works as a very simplistic front-controller pattern.
Most systems don’t map the URL to a single PHP file that is the page – they map the URL path to a controller that knows how to build the page.
In addition, not all URL’s need to map to a direct file. For example, look at
github.com/[username]/[repo]. You can’t create millions ofbob/ajaxstuff/index.phpfiles – you need to use regex to tell a controller you want the write page for this project.To really grasp how this should be used correctly I recommend you use a full-featured routing system like the simple Slim Framework.
If you want more information about routing design and theory I recommend reading php-router’s readme and the excellent URL Design post from warpspire.
If any of those are too much, you can also look at klein and the super-simple ToroPHP library.