I am designing a Q & A website use php. Here is the directory structure:
+include
db.php
user.php
template.php
...
question.php
+public
+images
+styles
.htaccess
index.php
...
I want to use index.php ‘s REQUEST_STRING to load a template.
For example: index.php?page=signin will load the function get_signin_template() in template.php. And will show the visitor a URL like http://example.com/signin/.
Here are my questions:
- How to load different templates in
index.php(what should do in this file)? - How to rewrite the url (using apache mod_rewrite)?
Answer to Question 1
See
call_user_func()in the PHP manual and thein_array()function in the PHP manual.I think it is also worth mentioning that I would not do it this way myself. Mapping URLs directly to functions is an inflexible way of doing things.
The reason I have added the
$valid_templatesarray is to ensure the user doesn’t attempt to change the URL in an attempt to call a nonexistant function etc. You would need to add each page/template function to it.If you really like this way of working then I would recommend you check out Limonade as it uses a similar dispatch method as the one you are attempting to setup (the following example is from their official site):
But is a little safer and easier to manage in my opinion. Plus all the “hard” plumbing work has been done and you can just focus on adding your pages.
Another similar option is Slim, which looks like this:
Example from their site.
Answer to Question 2
Something along these lines in your .htaccess file should work for your rewriting needs.