How to get page number from URL and include it like this?
I am working on a good solution for routing and including the correct pages in a social network type project I am working on. I have decided to run all my routing through a single entry point file. I do not wish to use an existing framework for this. If you review the sample code below you can see that it is pretty basic and should be good on performance for a high traffic site except I am stuck when it comes to modules that require paging. the whole point of this is to have clean looking URL's everywhere on the site.
So please help me with modifying to work with paging when there is a paging number in the URL.
(ie; domain.com/blogs/comments/234)
.htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ test.php?uri=$1 [NC,L,QSA]
test.php file
<?PHP
//get url from URL
$uri = isset( $_GET['uri'] ) ? $_GET['uri'] : null;
// Array of po开发者_如何学编程ssible pages to include
$pageId = array(
'account' => 'modules/account/index.php',
'account/create' => 'modules/account/create.php',
'account/settings' => 'modules/account/settings.php',
'account/login' => 'modules/account/login.php',
//example of a URL which will need paging....
'users/online/' => 'modules/users/online.php',
'users/online/12' => 'modules/users/online.php?page=12' // not sure if including a page like this is even possible?
);
// If $_GET['uri'] exist and there is a valid key/value for it in the $pageId array then include the file
if( $uri !== null ) {
if (isset($pageId[$uri])) {
require_once $pageId[$uri];
}
else {
require_once 'home.php';
}
}
else {
require_once 'home.php';
}
?>
I think you are doing some premature optimization here. Take a look at this discussion on quora about configuring apache for high traffic websites. I think it might help you.
http://www.quora.com/What-is-the-best-apache-conf-configuration-for-a-webserver-whose-handle-100-request-per-second-with-PHP-APC-enabled-and-htaccess-image-compression?q=requests+per+secont
Apart from that you should probably change the semantics of you $pageId
array from key
-> page
as it is today to a regex
-> replacement
array.
Something similar to this:
$pageId = array(
'account' => 'modules/account/index.php',
'account/create' => 'modules/account/create.php',
'account/settings' => 'modules/account/settings.php',
'account/login' => 'modules/account/login.php',
//example of a URL which will need paging....
'users/online/' => 'modules/users/online.php',
'users/online/(\d+)' => 'modules/users/online.php?page=$1'
);
And in your routing code you should iterate the array build a regular expression and match the url. When it matches you should do the replacement and you get the page to invoke. However if this is done straight forward it will kill your routing performance :(. A lot of frameworks do this already pretty well from that i know and i think you should try to take a look in there to see what you can borrow :).
精彩评论