php路由自动加载函数,如何在php路由中使用外部函数

Route::add('/', function(){

echo 'Hello world message';

});

我的挑战是。。。我希望能够直接从我正在调用的控制器加载函数

use Controllers\LoginController;

Route::add('/', LoginController::login());

我得到这个错误

Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given in C:\xampp\htdocs\Config\Route.php on line 75

我的路由.php

namespace Config;

class Route{ private static $routes = Array(); private static $pathNotFound = null; private static $methodNotAllowed = null;

public static function add($expression, $function, $method = 'get') {

array_push(self::$routes,Array(

'expression' => $expression,

'function' => $function,

'method' => $method

)); }

public static function pathNotFound($function){

self::$pathNotFound = $function; }

public static function methodNotAllowed($function){

self::$methodNotAllowed = $function; }

public static function run($basepath = '/')

{

// Parse current url

$parsed_url = parse_url($_SERVER['REQUEST_URI']);//Parse Uri

if(isset($parsed_url['path'])){

$path = $parsed_url['path'];

}else{

$path = '/';

}

// Get current request method

$method = $_SERVER['REQUEST_METHOD'];

$path_match_found = false;

$route_match_found = false;

foreach(self::$routes as $route){

// If the method matches check the path

// Add basepath to matching string

if($basepath!=''&&$basepath!='/'){

$route['expression'] = '('.$basepath.')'.$route['expression'];

}

// Add 'find string start' automatically

//$route['expression'] = '^'.$route['expression'];

// Add 'find string end' automatically

$route['expression'] = $route['expression'].'$';

//echo $path.'
';

// Check path match

if(preg_match('#'.$route['expression'].'#',$path,$matches)){

$path_match_found = true;

// Check method match

if(strtolower($method) == strtolower($route['method'])){

array_shift($matches);// Always remove first element. This contains the whole string

if($basepath!=''&&$basepath!='/'){

array_shift($matches);// Remove basepath

}

call_user_func_array($route['function'], $matches);

$route_match_found = true;

// Do not check other routes

break;

}

}

}

// No matching route was found

if(!$route_match_found){

// But a matching path exists

if($path_match_found){

header("HTTP/1.0 405 Method Not Allowed");

if(self::$methodNotAllowed){

call_user_func_array(self::$methodNotAllowed, Array($path,$method));

}

}else{

header("HTTP/1.0 404 Not Found");

if(self::$pathNotFound){

call_user_func_array(self::$pathNotFound, Array($path));

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值