PHP 新手入门指南 - 表单请求与路由

在之前的系列内容的基础上,这回我们尝试在页面上添加一个可以提交的表单,可以让用户提交相应的名称。

PHP 新手入门指南 - 表单请求与路由_第1张图片
表单

小实践

修改 index.view.php 文件中的内容为:



Submit Your Name

但这个表单页面没法正常处理,因为还需要:

  • 相应的路由配置
  • 正确解析 http://localhost:8000/names?name=Jacob 这样带参数的路径

所以,我们要在路由中 routes.php 添加新的路由配置:

'names' => 'controllers/add-name.php'

同时,修改 core/Request.php 让他可以正确解析路径:

修改之后的 uri 方法就可以从带有参数的 URL 中提取到正确的路径:

比如: http://localhost:8000/names?name=Jacob 将会是 names

另外我们还添加了一个方法 method 获取请求类型,后面将会用到。

我们可以在 add-name.php 可以打印表单提交的内容:

// controllers/add-name.php

很显然我们可以很好的处理 GET 请求,通过打印输出确实可以拿到 URL 参数。

接下来,我们要对 Router.php 做修改,希望可以通过 Router 类的不同的方法将 GET 请求和 POST 请求的路由定义区分开,实现如下效果:

$router->get('about', 'controllers/about.php');
$router->post('names', 'controllers/add-name.php');

修改 core/Router.php 的内容如下:

 [],
        'POST' => []
    ];

    public static function load($file)
    {
        $router = new static;

        require $file;

        return $router;
    }

    public function get($uri, $controller)
    {
        $this->routes['GET'][$uri] = $controller;
    }

    public function post($uri, $controller)
    {
        $this->routes['POST'][$uri] = $controller;
    }

    public function direct($uri, $requestType)
    {
        if (array_key_exists($uri, $this->routes[$requestType])) {
            return $this->routes[$requestType][$uri];
        }

        throw new Exception('No route defined for this URI.');
        
    }
}

接下来,routes.php 中的路由我们可以重新定义了,如下:

get('', 'controllers/index.php');
$router->get('about', 'controllers/about.php');
$router->get('about/culture', 'controllers/about-culture.php');
$router->get('contact-our-company', 'controllers/contact.php');
$router->post('names', 'controllers/add-name.php');

修改我们的程序入口文件 index.php:

direct(Request::uri(), Request::method());

为了看到 GETPOST 不同效果,我们可以在页面 index.view.php 中对表单请求类型进行调整:

因为我们定义的路由 names 必须是 POST 请求,所以这里改为 method="POST"routes.php 定义类型相对应。

运行看效果吧。

你可能感兴趣的:(PHP 新手入门指南 - 表单请求与路由)