2

我正在寻找有关如何进行非常基本的 php 路由的教程或说明。

例如,当我访问如下链接时:mywebsite.com/users 我想运行路由类的 get 方法来提供数据,就像 laravel 一样。

Route::get('users', function()
{
    return 'Users!';
});

有人可以解释如何做到这一点或向我提供更多信息吗?

4

3 回答 3

8

在其最常见的配置中,PHP 依赖于 Web 服务器来进行路由。这是通过将请求路径映射到文件来完成的:如果您请求 www.example.org/test.php,Web 服务器实际上会在预定义的目录中查找名为 test.php 的文件。

有一个特性对我们来说很方便:许多 Web 服务器还允许您调用 www.example.org/test.php/hello,它仍然会执行 test.php。PHP 使请求路径中的附加内容可通过$_SERVER['PATH_INFO']变量访问。在这种情况下,它将包含“/hello”。

使用它,我们可以构建一个非常简单的路由器,如下所示:

<?php

// First, let's define our list of routes.
// We could put this in a different file and include it in order to separate
// logic and configuration.
$routes = array(
    '/'      => 'Welcome! This is the main page.',
    '/hello' => 'Hello, World!',
    '/users' => 'Users!'
);

// This is our router.
function router($routes)
{
    // Iterate through a given list of routes.
    foreach ($routes as $path => $content) {
        if ($path == $_SERVER['PATH_INFO']) {
            // If the path matches, display its contents and stop the router.
            echo $content;
            return;
        }
    }

    // This can only be reached if none of the routes matched the path.
    echo 'Sorry! Page not found';
}

// Execute the router with our list of routes.
router($routes);

?>

为了简单起见,我没有将路由器设为一个类。但从这里开始,这也不应该成为问题。

假设我们将此文件命名为 index.php。我们现在可以调用 www.example.org/index.php/hello 来获得一个漂亮的“Hello, World!”。信息。或 www.example.org/index.php/ 获取主页。

该 URL 中的“index.php”仍然很难看,但我们可以通过 URL 重写来解决这个问题。在 Apache HTTPD 中,您将.htaccess在同一目录中放置一个包含以下内容的文件:

RewriteEngine on
RewriteRule ^(.*)$ index.php/$1

你来了!您自己的路由器,逻辑代码不到 10 行(不包括注释和路由列表)。

于 2014-01-06T23:32:15.960 回答
2

嗯......互联网上有很多用于php路由的框架。如果您愿意,可以从https://packagist.org/search/?q=route尝试。但老实说,如果您来自程序 PHP 世界,第一次可能会遇到问题。

如果您愿意,可以使用 Jesse Boyer 为我自己的项目编写的以下代码。您的应用程序结构应如下 -

[应用程序文件夹]

  • 索引.php
  • .htaccess
  • 路由.php

路由.php

<?php
/**
 * @author      Jesse Boyer <contact@jream.com>
 * @copyright   Copyright (C), 2011-12 Jesse Boyer
 * @license     GNU General Public License 3 (http://www.gnu.org/licenses/)
 *              Refer to the LICENSE file distributed within the package.
 *
 * @link        http://jream.com
 *
 * @internal    Inspired by Klein @ https://github.com/chriso/klein.php
 */

class Route
{
    /**
    * @var array $_listUri List of URI's to match against
    */
    private static $_listUri = array();

    /**
    * @var array $_listCall List of closures to call 
    */
    private static $_listCall = array();

    /**
    * @var string $_trim Class-wide items to clean
    */
    private static $_trim = '/\^$';

    /**
    * add - Adds a URI and Function to the two lists
    *
    * @param string $uri A path such as about/system
    * @param object $function An anonymous function
    */
    static public function add($uri, $function)
    {
        $uri = trim($uri, self::$_trim);
        self::$_listUri[] = $uri;
        self::$_listCall[] = $function;
    }

    /**
    * submit - Looks for a match for the URI and runs the related function
    */
    static public function submit()
    {   
        $uri = isset($_REQUEST['uri']) ? $_REQUEST['uri'] : '/';
        $uri = trim($uri, self::$_trim);

        $replacementValues = array();

        /**
        * List through the stored URI's
        */
        foreach (self::$_listUri as $listKey => $listUri)
        {
            /**
            * See if there is a match
            */
            if (preg_match("#^$listUri$#", $uri))
            {
                /**
                * Replace the values
                */
                $realUri = explode('/', $uri);
                $fakeUri = explode('/', $listUri);

                /**
                * Gather the .+ values with the real values in the URI
                */
                foreach ($fakeUri as $key => $value) 
                {
                    if ($value == '.+') 
                    {
                        $replacementValues[] = $realUri[$key];
                    }
                }

                /**
                * Pass an array for arguments
                */
                call_user_func_array(self::$_listCall[$listKey], $replacementValues);
            }

        }

    }

}

.htaccess

这里在第 2 行,而不是 '/php/cfc/' 您需要输入 localhost 项目目录名称,例如 'Application-folder'

RewriteEngine On
RewriteBase /php/cfc/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.+)$ index.php?uri=$1 [QSA,L]

索引.php

在 index.php 文件中,您需要编写以下代码 -

<?php 



include "route.php";





/**
 * -----------------------------------------------
 * PHP Route Things
 * -----------------------------------------------
 */

//define your route. This is main page route. for example www.example.com
Route::add('/', function(){

    //define which page you want to display while user hit main page. 
    include('myindex.php');
});


// route for www.example.com/join
Route::add('/join', function(){
    include('join.php');
});

Route::add('/login', function(){
    include('login.php');
});

Route::add('/forget', function(){
    include('forget.php');
});



Route::add('/logout', function(){
    include('logout.php');
});





//method for execution routes    
Route::submit();

这对我来说非常有用。希望它也对你有用......

快乐编码... :)

于 2015-07-01T17:28:05.460 回答
0

好吧,它可以通过使用在原生 PHP 中创建一个 PHP 路由系统

  • 本机 PHP(无 laravel)
  • .htaccess

这显示了如何在几分钟内设置 php 路由系统: https ://www.youtube.com/watch?v=ysnW2mRbZjE

于 2021-12-21T21:32:17.667 回答