Alto Router not working for controllers

陌路散爱 提交于 2020-01-15 10:15:28

问题


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

in index.php i have following code

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

Controller

class HomeController extends Controller{

    public function __construct()
    {
        echo "hello, i am a page.";
    }

    public function index(){


        echo "hello, i am a page.";
    }

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] => 
)

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


回答1:


How do you load the HomeController?

Take this example

$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



来源:https://stackoverflow.com/questions/42883436/alto-router-not-working-for-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!