fenci/app/helper/Router.php
2020-09-30 19:56:27 +08:00

55 lines
1.4 KiB
PHP

<?php
namespace app\helper;
use app\Api;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;
class Router
{
private static $Routes = [];
private static $Instance = [];
private function __construct()
{
}
/**
* @param $path
* @param $handler
*/
public static function add($path, $handler)
{
self::$Routes[$path] = $handler;
}
public static function process(Request $request)
{
$path = $request->path();
echo "[INFO]", date('h:i:s'), " request {$path} \n";
if (isset(self::$Routes[$path])) {
try{
$handler = self::$Routes[$path];
if(!isset(self::$Instance[$handler])){
echo "[INFO]", date('H:i:s'), " initial instance of {$handler}\n";
self::$Instance[$handler] = new $handler();
}
if (self::$Instance[$handler] instanceof Api) {
$result = self::$Instance[$handler]->handle($request);
if($result instanceof Response){
return $result;
}
return new Response(200, [], $result);
}
}catch (\Exception $e){
return new Response(500, [], $e->getMessage());
}
// print_r($handler);
}
return new Response(200, [], '404');
}
}