Alto路由器不适用于控制器

Alto路由器不适用于控制器

本文介绍了Alto路由器不适用于控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将控制器名称和方法传递给Alto Router映射方法,但不起作用

I am trying pass controller name and method to Alto Router map method but it doesnt work

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.";
    }

如果我访问然后,其工作但非控制器url,但抛出错误

if i access http://localhost/demo/php then its working but not controller url but its throwing error

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

    [name] =>
)

有人可以帮助我吗如何解决?
,也可以通过 require_once'vendor / autoload.php'; 一次,而不是在所有页面中添加

can any one help me how to fix it ?and also is there way to require_once 'vendor/autoload.php'; only once instead of adding in all pages

推荐答案

如何加载HomeController?

How do you load the 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';
    }
}

此方法有效,其余部分需要根据进行修改您的网站结构

This works, rest you need to modify it according to your site structure

这篇关于Alto路由器不适用于控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 15:09