การทำ Router ให้เว็บไซต์ด้วย PHP
2022-03-22 Games 7702022-04-06 Games
class ที่นำมาใช้งาน SimpleRouter
โครงสร้าง Directory
back/.htaccess
back/index.php
back/lib/class/router.php
router.php
<?php
class SimpleRouter
{
/* Routes array where we store the various routes defined. */
private $routes;
/* The methods adds each route defined to the $routes array */
function add_route($route, callable $closure)
{
$this->routes[$route] = $closure;
}
/* Execute the specified route defined */
function execute()
{
$path = urldecode($_SERVER['REQUEST_URI']);
$path = filter_var($path, FILTER_SANITIZE_URL);
$path = strtok($path, '?');
$chk_html = strpos($path,'.html');
if($chk_html!=0){
$path = str_replace('.html', '', $path);
$path_array = explode('-', $path);
$modules = $path_array[0];
} else {
$modules = '/404';
}
if($path=='/'.ADMIN_FOLDER.'/'){
$modules = '/'.ADMIN_FOLDER.'/login';
}
if (array_key_exists($modules, $this->routes)) {
$this->routes[$modules]();
} else {
$this->routes['/404']();
}
}
}.htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ back/index.php [QSA,L]index.php
<?php
define('ADMIN_FOLDER', 'back');
include(dirname(__FILE__).'/lib/class/router.php');
$path = strtok($path, '?');
$pattern = "/(.*)(.html$)/";
$chk_html = strpos($path,'.html');
/* check การเข้ามาด้วย .html ถ้าไม่ได้เข้ามาด้วย .html ให้ไปหน้า 404
ออกแบบ url ที่เข้ามา รับด้วย html ทั้งหมด
module-method-id.html
article-add.html
article-edit-1.html
user-profile.html
*/
if($chk_html!=0){
$path = str_replace('.html', '', $path);
$path = str_replace('/'.ADMIN_FOLDER.'/', '', $path);
$path_array = explode('-', $path);
$modules = $path_array[0];
} else {
$modules = '404';
}
if($path=='/back/'){
$modules = 'login';
}
$menu = (isset($path_array[1]))? $path_array[1] : '';
$id = (isset($path_array[2]))? $path_array[2] : '';
/* Create a new router */
$router = new SimpleRouter();
/* Add a Homepage route as a closure */
$router->add_route('/'.ADMIN_FOLDER.'/'.$modules, function () {
global $path;
global $modules;
global $menu;
global $id;
if(file_exists(dirname(__FILE__) . '/modules/'.$modules.'.php')){
include(dirname(__FILE__) . '/modules/'.$modules.'.php');
} else {
include(dirname(__FILE__) . '/modules/login/404.php');
}
});
$router->add_route('/404', function () {
include(dirname(__FILE__) . '/modules/login/404.php');
});
/* Execute the router */
$router->execute();ที่มา & ข้อมูลให้ศึกษาเพิ่มเติม
Router,PHP | PHP
