小编给大家分享一下关于PHP中DIY系列之自定义配置和路由的案例,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
我们已经开发完成,但我们还需要更多。比如自定义配置和路由。
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);
/**
* 执行结果赋值给$response->data,并返回给response对象
*/
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);
...省略代码
保存后打开浏览器看看效果:
这里虽然有自定义路由,但是我们有时候需要禁止默认路由,所以我们不妨增加配置参数defaultRoute,用来控制是否开启默认路由。
我们修改一下路由解析的代码:
//Application...省略代码
public function handleRequest(Request $request){
$route = $request->resolve($this->_config['route']??[]);
$response = $request->runAction($route, $this->_config['defaultRoute']??true);
/**
* 执行结果赋值给$response->data,并返回给response对象
*/
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);
}
...省略代码
我们在app下面的Config,加入:
return [
'debug' => false,
'route' => [
'' => 'demo/welcome',
'test' => 'demo/test',
],
'defaultRoute' => false,];
我们打开浏览器输入saif.com/login
报错如下:
Array
(
[line] => 137
[msg] => route not found:login
[code] => 404
[file] => library/Https/Request.php
)
看完了这篇文章,相信你对关于PHP中DIY系列之自定义配置和路由的案例有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。