PHP Router,.htaccess和重写查询字符串

问题描述 投票:0回答:1

我尝试搜索此问题,但没有找到能解决我问题的方法-我几乎可以确定我没有输入正确的搜索内容,因为我想这对其他人也是一个问题。如果我要击败一匹死马,请指出正确的方向,谢谢。

现有代码

我正在建立一种MVC框架。

。htaccess将所有请求路由到index.php

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]
<?php

require_once "./core/init.php";

Router::create( "./core/router/routes.php" )->direct( Request::uri(), Request::method() );

我的router.class.php文件:

<?php

class Router {

    protected $routes = array(

        "GET" => array(),

        "POST" => array()

    );

    public static function create( $routes ) {

        $router = new static;

        include $routes;

        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, $method ) {

        if ( array_key_exists( $uri, $this->routes[ $method ] ) ) {

            include $this->routes[ $method ][ $uri ];

        } else {

            include $this->routes[ "GET" ][ "not-found" ];

        }

    }

}

路由在routes.php中定义,就像这样(只是显示了相关的路由):

$router->get( "post", "controllers/get/post.controller.php" );

我的问题

当前导航到下面显示了该帖子,并且使用该插件从数据库中检索了该帖子。

/post?p=my-post-name

我该如何重写路由器或.htaccess,以使相同的帖子显示在以下URL中?

/post/my-post-name
php .htaccess routing
1个回答
0
投票

因此,最后,我通过在定向路由器之前创建检查来解决此问题,不确定该方法是否正确。

这基本上是针对数组检查URI,并且如果URI包含以下设置值之一,则将其解构,最后一个值将存储在名为get的变量中,然后将URI重构为假的查询字符串:

// index.php

require_once "./core/init.php";

$uri = Request::uri();

/*
 * Fake query strings
 */
$uriParts = explode( "/", $uri );
$queryPages = array( "post", "category", "edit-post" );

foreach ( $queryPages as $queryPage ) {

    if ( in_array( $queryPage, $uriParts ) ) {

        $get = $uriParts[ count( $uriParts ) - 1 ];
        array_pop( $uriParts );
        $uri = "";

        for ( $i = 0; $i < ( count( $uriParts ) ); $i++ ) {

            $uri .= $uriParts[ $i ] . "/";

        }

        $uri = trim( $uri, "/" );
        break;

    }

}

Router::create( "./core/router/routes.php" )->direct( $uri, Request::method() );

以上内容适用于各种深度的URI:

post/my-post
category/general
admin/posts/edit-post/my-post

“查询字符串”可以在带有global $get;的控制器中使用,然后代替$_GET。这不适用于多个查询,但非常适合我的需求。

© www.soinside.com 2019 - 2024. All rights reserved.