【问题标题】:Alto Router not working for controllers中音路由器不适用于控制器
【发布时间】:2017-03-19 06:00:05
【问题描述】:

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

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://localhost/demo/php 那么它的工作但不是控制器 url 但它的抛出错误

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

    [name] => 
)

谁能帮我解决它? 还有没有办法require_once 'vendor/autoload.php'; 一次而不是添加所有页面

【问题讨论】:

    标签: php laravel codeigniter routing altorouter


    【解决方案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';
        }
    }
    

    这个可行,剩下的你需要根据你的网站结构修改它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      相关资源
      最近更新 更多