我們已經(jīng)開(kāi)發(fā)完成,但我們還需要更多。比如自定義配置和路由。
app文件夾下新建Config.php
<?php/**
*自定義配置
*/return [
'debug' => false,
'route' => [
'' => 'demo/welcome',
'test' => 'demo/test',
],];
新建DemoController(app/Https/Controllers目錄下)
<?php/**
* Demo控制器
*/namespace App\\\\Https\\\\Controllers;use Library\\\\Https\\\\Controller;class DemoController extends Controller{
public function welcome($params)
{
return $this->response->json(['hello' => 'welcome']);
}
public function test($params)
{
return $this->response->json($params);
}}
修改入口文件index.php,加入加載配置代碼:
... 省略代碼 // 加載配置 $config = require SF_LIBRARY_PATH.'Config.php'; $appConfig = file_exists($appConfigPath = SF_APP_PATH.'Config.php') ? require $appConfigPath : []; $config = array_merge($config, $appConfig); $config['debug'] = ($config['debug']?? SF_DEBUG); ...省略代碼
解析路由部分也加入自定義路由處理:
// Application...省略代碼
public function handleRequest(Request $request){
$route = $request->resolve($this->_config['route']??[]);
$response = $request->runAction($route);
/**
* 執(zhí)行結(jié)果賦值給$response->data,并返回給response對(duì)象
*/
if ($response instanceof Response) {
return $response;
}
throw new SaiException('Content format error');}
...省略代碼
public function resolve($route=[]) {
$this->route = $route; // 自定義路由
return $this->getPathUrl(); }
// Request
...省略代碼public function runAction($route){
if (array_key_exists($route, $this->_route)) {
$route = $this->_route[$route];
}
$match = explode('/', $route);
$match = array_filter($match);
...省略代碼
保存后打開(kāi)瀏覽器看看效果:
這里雖然有自定義路由,但是我們有時(shí)候需要禁止默認(rèn)路由,所以我們不妨增加配置參數(shù)defaultRoute,用來(lái)控制是否開(kāi)啟默認(rèn)路由。
我們修改一下路由解析的代碼:
//Application...省略代碼
public function handleRequest(Request $request){
$route = $request->resolve($this->_config['route']??[]);
$response = $request->runAction($route, $this->_config['defaultRoute']??true);
/**
* 執(zhí)行結(jié)果賦值給$response->data,并返回給response對(duì)象
*/
if ($response instanceof Response) {
return $response;
}
throw new SaiException('Content format error');}
...省略代碼
...省略代碼
public function runAction($route, $defaultRoute){
if (array_key_exists($route, $this->_route)) {
$route = $this->_route[$route];
} elseif (!$defaultRoute) {
throw new NotFoundException("route not found:".$route);
}
...省略代碼
我們?cè)赼pp下面的Config,加入:
return [
'debug' => false,
'route' => [
'' => 'demo/welcome',
'test' => 'demo/test',
],
'defaultRoute' => false,];
我們打開(kāi)瀏覽器輸入saif.com/login
報(bào)錯(cuò)如下:
Array
(
[line] => 137
[msg] => route not found:login
[code] => 404
[file] => library/Https/Request.php
)
相關(guān)學(xué)習(xí)推薦:PHP編程從入門(mén)到精通
更多關(guān)于云服務(wù)器,域名注冊(cè),虛擬主機(jī)的問(wèn)題,請(qǐng)?jiān)L問(wèn)西部數(shù)碼官網(wǎng):www.ps-sw.cn