Home > Backend Development > PHP Problem > There are several ways to write routing in php

There are several ways to write routing in php

(*-*)浩
Release: 2023-02-25 12:56:01
Original
9545 people have browsed it

The function of routing is to distribute requests to different controllers, based on the principle of regular matching. Next, we implement a simple router that can correctly call callbacks for static routes (without placeholders).

There are several ways to write routing in php

Route distribution(Recommended learning: PHP video tutorial)

PHP-based route distribution, essence To put it simply, it is to use the path in the URL to match the corresponding control class, and at the same time call the methods in it to process related operations.

<?php
// 权限控制
include_once &#39;./auth.php&#39;;

// 应用入口文件
date_default_timezone_set("Asia/Shanghai");
header(&#39;Content-type: text/html;charset=utf-8&#39;);
// 项目根路径
define(&#39;BASEPATH&#39;, dirname(__FILE__));
// 调试模式
define(&#39;APP_DEBUG&#39;, True);

// 引入配置文件
include_once BASEPATH . &#39;/config/config.php&#39;;

// 路由控制
$router = include_once BASEPATH . &#39;/config/router.php&#39;;
if ($_SERVER[&#39;HTTP_HOST&#39;] !== &#39;xxx.com&#39;) {
    var_dump(&#39;当前host不被允许&#39;);
} else {
    $request_path = str_replace(&#39;/index.php&#39;, &#39;&#39;, $_SERVER[&#39;PHP_SELF&#39;]);
    $request_query = getCurrentQuery();
    if (array_key_exists($request_path, $router)) {
        $module_file = BASEPATH . $router[$request_path][&#39;file_name&#39;];
        $class_name = $router[$request_path][&#39;class_name&#39;];
        $method_name = $router[$request_path][&#39;method_name&#39;];
        if (file_exists($module_file)) {
            include $module_file;
            $obj_module = new $class_name();
            if (!method_exists($obj_module, $method_name)) {
                die("要调用的方法不存在");
            } else {
                if (is_callable(array($obj_module, $method_name))) {
                    $obj_module->$method_name($request_query, $_POST);
                }
            }
        } else {
            die("定义的模块不存在");
        }
    } else {
        echo &#39;页面不存在&#39;;
    }
}
Copy after login

The above is the detailed content of There are several ways to write routing in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template