How does the Router in the php MVC framework work (with code)

不言
Release: 2023-04-03 14:04:01
Original
3446 people have browsed it

This article brings you an article about how the router (Router) in the php MVC framework works (with code). The content is very good. Friends in need can refer to it. I hope it can help everyone.

Note: There seems to be a bug in the SF translation category, so this article is given in the original category.

MVC Router or Dispatcher will detect the URL of the HTTP request and try to match a single URL component with the controller and the method defined in the controller, while passing all parameters into the method .

A simple router class is given below to roughly illustrate how the router works. However, in a real project, the router is much more complex than the example router below because it has to deal with more things. The

<?php

class SimpleRouter
{
    // 路由数组,存储我们定义的路由
    private $routes;

    // 这个方法用于将定义的路由加入到 $routes 数组
    function add_route($route, callback $closure)
    {
        $this->routes[$route] = $closure;
    }

    // 执行特定的路由
    function execute()
    {
        $path = $_SERVER['PATH_INFO'];

        /**
        * 检测给定路由是否被定义,
        * 或者执行默认的 '/' 首页路由。
        */
        if (array_key_exists($path, $this->route)) {
            $this->route[$path]();
        } else {
            $this->route['/]();
        }
    }
}
Copy after login

SimpleRouter class is a simplified model of an MVC router. Its main function is to add each user-defined route to an array and execute it. To understand how it works, copy the code below into the index.php file.

<?php

// index.php

class SimpleRouter
{
    // 路由数组,存储我们定义的路由
    private $routes;

    // 这个方法用于将定义的路由加入到 $routes 数组
    function add_route($route, callback $closure)
    {
        $this->routes[$route] = $closure;
    }

    // 执行特定的路由
    function execute()
    {
        $path = $_SERVER['PATH_INFO'];

        /**
        * 检测给定路由是否被定义,
        * 或者执行默认的 '/' 首页路由。
        */
        if (array_key_exists($path, $this->route)) {
            $this->route[$path]();
        } else {
            $this->route['/]();
        }
    }
}

/* 创建 Router 实例 */
$router = new SimpleRouter();
 
/* 添加首页闭包值路由器 */
$router->add_route('/', function(){
    echo 'Hello World';
});
 
/* 添加另一个闭包路由 */
$router->add_route('/greetings', function(){
    echo 'Greetings, my fellow men.';
});
 
/* 添加可回调函数作为路由 */
$router->add_route('/callback', 'myFunction');
 
 
/* 回调函数处理程序 */
function myFunction(){
    echo "This is a callback function named '" .  __FUNCTION__ ."'";
}

/* 执行路由 */
$router->execute();
Copy after login

Now go to your browser and visit the following urls:

http://localhost/index.php/
http://localhost/index.php/greetings
http://localhost/index.php/callback
Copy after login

For each url, you should see a different message defined in our route. So how does the router work?

In our example, the add_route method adds the path name (route) of the url to the routing array and defines the corresponding processing operation. This processing operation can be a simple function or callback function, passed in as a closure. Now when we execute the router's execute method, it will detect whether a route is matched in the current $routes array, and if so, execute this function or callback function.

If you use var_dump this $routes array, you can see the specific contents of the array. For each defined route a closure is stored associated with it.

array (size=3)
  '/' => 
    object(Closure)[2]
  '/greetings' => 
    object(Closure)[3]
  '/callback' => string 'myFunction' (length=10)
Copy after login

Execution processing is completed by the following lines. $this->routes[$path]** statement returns a closure, which is stored in the **\$routes array and is used to specify the execution of the route. Note the ().

$this->routes[$path]();
// 或
$this->routes['/']();
Copy after login

The above example simply demonstrates how the router works. For the sake of simplicity, we do not handle any errors and do not consider routing security issues.

Related recommendations:

PHP MVC framework routing study notes, mvc framework routing study notes

##PHP learning MVC framework routing

The above is the detailed content of How does the Router in the php MVC framework work (with code). For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!