[英]Alto Router not working for controllers
I am trying pass controller name and method to Alto Router map method but it doesnt work 我正在尝试将控制器名称和方法传递给Alto Router映射方法,但它不起作用
in index.php
i have following code 在
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);
}
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 如果我访问http:// localhost / demo / php然后它的工作但不是控制器url但它的抛出错误
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';
还有办法来
require_once 'vendor/autoload.php';
only once instead of adding in all pages 只有一次而不是添加所有页面
How do you load the HomeController? 你如何加载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 这是有效的,您需要根据您的网站结构进行修改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.