【问题标题】:Routing via Php AltoRouter通过 Php AltoRouter 路由
【发布时间】:2016-11-04 03:07:01
【问题描述】:

我第一次尝试使用路由器(AltoRouter),无法调用任何页面。

网页文件夹结构

代码

索引.php

require 'lib/AltoRouter.php';

$router = new AltoRouter();
$router->setBasePath('/alto');
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET|POST','/', 'display.php', 'display');
$router->map('GET','/plan/', 'plan.php', 'plan');
$router->map('GET','/users/', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');
// match current request
$match = $router->match();

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');
}

我在计划文件夹中有一个名为 plan.php(显示计划)的文件,我正在尝试的超链接是

<a href="<?php echo $router->generate('plan'); ?>">Plan <?php echo $router->generate('plan'); ?></a>

这不起作用。

你能帮忙吗?

【问题讨论】:

    标签: php routing routes router altorouter


    【解决方案1】:

    您不能通过将plan.php 作为参数传递给match 函数来调用plan.php

    http://altorouter.com/usage/processing-requests.html查看示例

    如果你想使用 plan.php 中的内容

    您应该使用以下格式的map

    $router->map('GET','/plan/',  function() {
        require __DIR__ . '/plan/plan.php';
    } , 'plan');
    

    到文件plan/plan.php 添加echo 'testing plan';

    另外,请仔细检查您的 .htaccess 文件是否包含

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.php [L]
    

    此外,如果您使用$router-&gt;setBasePath('/alto'); 设置基本路径,则您的index.php 文件应放在alto 目录中,这样您的网址就会在这种情况下为http://example.com/alto/index.php

    工作示例:

    require 'lib/AltoRouter.php';
    
    $router = new AltoRouter();
    $router->setBasePath('/alto');
    
    $router->map('GET','/plan/',  function(  ) {
        require __DIR__ . '/plan/plan.php';
    } , 'plan');
    
    // match current request
    $match = $router->match();
    
    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');
    }
    

    这样就可以了

    <a href="<?php echo $router->generate('plan'); ?>">Plan <?php echo $router->generate('plan'); ?></a>
    

    【讨论】:

    • 我的主页正常工作,但无法调用 plan.php。主页有一个指向计划 Plan 的链接,我将其更改为 Plan generate('plan'); ?>.
    • home#index 这很有效,因为您很可能有 Home 类,其中包含方法索引。 $router->map('GET','/plan/', function() { 需要 DIR . '/plan/plan.php'; } , 'plan');当路由匹配时,上面的这个函数包含 plan.php 文件。或者,您可以使用方法索引创建类plan,然后您将能够以与主页相同的方式传递plan#index。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 2015-07-10
    • 2015-02-07
    • 2011-09-23
    • 2012-03-30
    相关资源
    最近更新 更多