php router有案例嗎

PHP
小樊
81
2024-10-17 16:30:57

當(dāng)然有!下面是一個(gè)簡(jiǎn)單的PHP路由案例,使用了內(nèi)置的$_SERVER['REQUEST_URI']變量來(lái)解析請(qǐng)求的URI,并根據(jù)URI調(diào)用相應(yīng)的控制器方法。

<?php
// 路由定義
$routes = [
    '/' => 'HomeController@index',
    '/about' => 'AboutController@index',
    '/contact' => 'ContactController@index',
];

// 路由解析
$requestUri = $_SERVER['REQUEST_URI'];
$routeFound = false;
$controllerMethod = '';

foreach ($routes as $route => $handler) {
    if (strpos($requestUri, $route) === 0) {
        $routeFound = true;
        list($controller, $method) = explode('@', $handler);
        break;
    }
}

// 路由處理
if ($routeFound) {
    // 調(diào)用控制器方法
    $controllerInstance = new $controller();
    call_user_func_array([$controllerInstance, $method], []);
} else {
    // 處理404錯(cuò)誤
    echo '404 Not Found';
}
?>

在這個(gè)例子中,我們定義了三個(gè)路由://about/contact,分別對(duì)應(yīng)HomeController、AboutControllerContactControllerindex方法。當(dāng)用戶(hù)訪(fǎng)問(wèn)這些URL時(shí),PHP腳本會(huì)解析請(qǐng)求的URI,并根據(jù)URI調(diào)用相應(yīng)的控制器方法。

請(qǐng)注意,這個(gè)例子僅用于演示目的,實(shí)際項(xiàng)目中通常會(huì)使用更復(fù)雜的路由系統(tǒng),例如Laravel框架中的路由系統(tǒng)。

0