Altorouter不知道如何正确路由PHP


Altorouter cant figure out how to route correctly PHP

如果您以前没有使用过,则链接为:http://altorouter.com/

我正在制作一个小型应用程序,但不需要框架,只需要路由部分。所以我决定试试altorouter,因为它看起来很简单。

我想绘制某些路线来做某些事情。例如:

www.example.com/products/

这应该显示我的products.php模板,并从数据库中提取数据来填充字段。我已经得到了以下工作:

$router->map( 'GET', '/products', function() {
    require('partials/connectdb.php'); //Require Database Connection
    $pageContent = getProductsContent($conn); //prepare all the page content from database
    require __DIR__ . '/products.php'; //require the template to use
});

所有其他标准页面也是如此,我的问题是路线何时可以更改。例如:

www.example.com/shoes/

www.example.com/shorts/

www.example.com/shirts/

www.example.com/ties/

当用户转到这些路线时,我想获得参数"shoes",然后在仍然使用products.php模板的同时,只为shoes执行逻辑。

所以看看它说你可以做的文档:

www.example.com/[*]//这意味着什么。

然而,在将其添加到我列出的路线中后,它会清空用户试图访问的任何其他内容。因此,如果他们访问:

www.example.com/products//就像之前一样

它实际上执行内部逻辑:

www.example.com/[*]

有人认识阿谁,能帮我吗?我将在下面粘贴我的完整页面代码:

// Site Router
$router->map( 'GET', '/', function() {
    require('partials/connectdb.php'); //Require Database Connection
    $pageContent = getHomeContent($conn);
    require __DIR__ . '/home.php';
});

$router->map( 'GET', '/products', function() {
    require('partials/connectdb.php'); //Require Database Connection
    $pageContent = getProductsContent($conn);
    require __DIR__ . '/products.php';
});

$router->map( 'GET', '/[*]', function($id) {
    require('partials/connectdb.php'); //Require Database Connection

    $test = 'this was a test';
    $pageContent = getProductsContent($conn);
    require __DIR__ . '/products.php';
});
// match current request url
$match = $router->match();
// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
    call_user_func_array( $match['target'], $match['params'] );
} else {
    // no route was matched
    header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}

您的url应该是

www.example.com/products/

www.example.com/products/shoes

www.example.com/products/shirts

然后你可以这样做:

$router->map( 'GET', '/products/:type', function($type) {
   require('partials/connectdb.php'); //Require Database Connection
   if(!isset($type)){
     $pageContent = getProductsContent($conn); //prepare all the page content from database
     require __DIR__ . '/products.php'; //require the template to use
    if($type == 'shoes'){
      //do this
      echo 'shoes';
    }
    if($type == 'shirts'){
      //do that
      echo 'shirts';
    }
});