奥拓路由器不能正常工作的控制器(Alto Router not working for contro

2019-09-30 14:09发布

我试图通过控制器名称和方法奥拓路由器映射方法,但它不工作

index.php我有以下代码

    <?php

    require_once 'vendor/autoload.php';

    use Route\AltoRouter;
    use App\Controllers\HomeController;

    $router = new AltoRouter();

    $router->setBasePath('demo/');
    $router->map('GET','/', 'HomeController#index');
    $router->map('GET', '/php', function(){

        echo 'It is working';
    });
$match = $router->match();

// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
    call_user_func_array( $match['target'], $match['params'] ); 
} else {

    echo "<pre>";
    print_r($match);
}

调节器

 class HomeController extends Controller{ public function __construct() { echo "hello, i am a page."; } public function index(){ echo "hello, i am a page."; } 

如果我访问的http://本地主机/演示/ PHP那么它的工作,但没有控制器的URL,但它的投掷的错误

Array
(
    [target] => HomeController#index
    [params] => Array
        (
        )

    [name] => 
)

任何一个可以帮助我如何解决它? 并且也有办法require_once 'vendor/autoload.php'; 只有一次,而在所有的网页添加

Answer 1:

你如何加载HomeController的?

就拿这个例子

$router = new AltoRouter();
$router->setBasePath('/AltoRouter'); 

$router->map('GET','/', 'home_controller#index', 'home');
$router->map('GET','/content/[:parent]/?[:child]?', 'content_controller#display_item', 'content');

$match = $router->match();

// not sure if code after this comment  is the best way to handle matched routes
list( $controller, $action ) = explode( '#', $match['target'] );

if ( is_callable(array($controller, $action)) ) {

    $obj = new $controller();
    call_user_func_array(array($obj,$action), array($match['params']));

} else if ($match['target']==''){
    echo 'Error: no route was matched'; 

} else {
    echo 'Error: can not call '.$controller.'#'.$action; 

}

// Can be placed in a different directory but needs to be loaded
class home_controller {
    public function index() {
        echo 'hi from home';
    }
}

这工作,休息需要修改它根据您的网站结构



文章来源: Alto Router not working for controllers