仿照Laravel的Request
[前言]
我們在上一章已經(jīng)能把項目通過composer上fast-router產(chǎn)生對應(yīng)關(guān)系,我們這一章繼續(xù)優(yōu)化我們的項目。
/**
* 分發(fā)路由
*/
public static function Route()
{
if (self::$routeInfo[0] !=0){
//把方法、控制器根據(jù)@符號炸開
$routerMessage = explode('@', self::$routeInfo[1]);
//由于我們控制都是在app/的Controller里面我們這里為什么可以大寫由于自動加載做了對應(yīng)關(guān)系
$controller = 'App\\Controller\\' . $routerMessage[0];
$controller = str_replace('/','\\',$controller);
$action = $routerMessage[1];
$obj = new $controller;
self::$htmlresult=$obj->$action();
}else{
throw new ErrorException('路由錯誤!請檢查路由是否正確!');
}
}
public static function send()
{
$res = self::$htmlresult;
if (gettype($res) == 'string') {
//字符串
echo $res;
} else {
echo json_encode($res);
}
}
上面使用了$htmlresult靜態(tài)變量裝數(shù)據(jù),在send方法輸出,在判斷如果不是字符串,是數(shù)組、對象會自動把數(shù)據(jù)轉(zhuǎn)換成json并返回。
我們在使用laravel發(fā)現(xiàn)這個框架里邏輯函數(shù)中,存在一些有時候會有Request $request的情況,有時候又可以沒有,怎么實現(xiàn)?
我在翻閱了google,baidu都搜尋過都沒有解決的辦法,怎么這個那么有意思的東西都沒人有好奇心呢?難道每個人都知道嗎?
我們在本項目中Request類就是用來過濾一些post、get一些不安全的數(shù)據(jù)。
于是乎我在上php官方手冊查閱的時候想到一個可行的辦法解決這個問題——反射
php手冊
我們動手開始操作。
public static function Route()
{
if (self::$routeInfo[0] !=0){
$routerMessage = explode('@', self::$routeInfo[1]);
$controller = 'App\\Controller\\' . $routerMessage[0];
$controller = str_replace('/','\\',$controller);
$action = $routerMessage[1];
$obj = new $controller;
//通過反射獲得參數(shù)
$reflection = new \ReflectionMethod($controller, $action);
$actionParameters=$reflection->getParameters();
//獲取到方法參數(shù)為一個類
if (!empty($actionParameters)){
//如果參數(shù)不為空
foreach ($actionParameters as $actionP){
$parame=$actionP->getType()->getName();
}
$parameters=new $parame;
self::$htmlresult=$obj->$action($parameters);
}else{
//如果參數(shù)為空
self::$htmlresult = $obj->$action();
}
}else{
throw new ErrorException('路由錯誤!請檢查路由是否正確!');
}
}
我們在libs類庫中創(chuàng)建Request.php類
<?php
/**
*
* Request.php
* User: kalvin
* Date: 2018/2/5
* Time: 下午4:49
*/
namespace libs;
class Request
{
public function get($getkey){
echo $getkey;
}
}
IndexController中的showIndex方法我們可以試下無論有無Request參數(shù)都可正確使用
<?php
/**
*
* IndexController.php
* User: kalvin
* Date: 2018/2/5
* Time: 下午4:22
*/
namespace App\Controller\Back\View;
use libs\Request;
class IndexController
{
public function showIndex(Request $request)
{
return '你好';
}
}