在Altorouter中调用控制器的方法

时间:2017-01-03 17:24:23

标签: php model-view-controller router altorouter

我一直在尝试使用altorouter获取Home控制器的index()方法,但我无法做到。我搜索过几个地方,但找不到任何帮助。

这是index.php

<?php

include 'system/startup.php';
include 'library/AltoRouter.php';

// Router
$router = new AltoRouter();
// Change here before upload
$router->setBasePath('/demo');
$router->map('GET|POST','/', 'home#index', 'home');

// match current request
$match = $router->match();

if( $match && is_callable( $match['target'] ) ) {
    call_user_func_array( $match['target'], $match['params'] ); 
} else {
    // no route matched
    header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}

目录&gt;控制器目录中的家庭控制器。

<?php
class home {
    public function index() {
        echo 'home';
    }
}

任何人都可以使用或曾经使用过这个altorouter指南吗?。

P.S。我在startup.php文件中有自动加载功能(包含在index.php的顶部)

1 个答案:

答案 0 :(得分:0)

这是旧帖子,但这可以帮到你。您需要以不同的方式提出匹配请求:

<?php

include 'system/startup.php';
include 'library/AltoRouter.php';

// Router
$router = new AltoRouter();
$router->setBasePath('/demo');
$router->map('GET|POST','/', 'home#index', 'home');
$match = $router->match();

if ($match === false) {
    // here you can handle 404
} else {
    list( $controller, $action ) = explode( '#', $match['target'] );
    if ( is_callable(array($controller, $action)) ) {
        call_user_func_array(array($controller,$action), array($match['params']));
    } else {
        // here your routes are wrong.
        // Throw an exception in debug, send a  500 error in production
    }
}