我是靠谱客的博主 大意书本,这篇文章主要介绍PHP DIY系列之自定义配置和路由,现在分享给大家,希望可以做个参考。


我们已经开发完成,但我们还需要更多。比如自定义配置和路由。

app文件夹下新建Config.php

复制代码
1
2
3
4
5
6
7
8
<?php/** *自定义配置 */return [ 'debug' => false, 'route' => [ '' => 'demo/welcome', 'test' => 'demo/test', ],];
登录后复制

新建DemoController(app/Https/Controllers目录下)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
<?php/** * Demo控制器 */namespace AppHttpsControllers;use LibraryHttpsController;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,加入加载配置代码:

复制代码
1
2
3
4
5
6
7
... 省略代码 // 加载配置 $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); ...省略代码
登录后复制

解析路由部分也加入自定义路由处理:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 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); ...省略代码
登录后复制

保存后打开浏览器看看效果:

image

image

这里虽然有自定义路由,但是我们有时候需要禁止默认路由,所以我们不妨增加配置参数defaultRoute,用来控制是否开启默认路由。

我们修改一下路由解析的代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//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');} ...省略代码
登录后复制
复制代码
1
2
3
4
5
6
7
8
...省略代码 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,加入:

复制代码
1
2
3
4
5
6
7
return [ 'debug' => false, 'route' => [ '' => 'demo/welcome', 'test' => 'demo/test', ], 'defaultRoute' => false,];
登录后复制

我们打开浏览器输入saif.com/login

报错如下:

复制代码
1
2
3
4
5
6
7
Array ( [line] => 137 [msg] => route not found:login [code] => 404 [file] => library/Https/Request.php )
登录后复制

以上就是PHP DIY系列之自定义配置和路由的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是大意书本最近收集整理的关于PHP DIY系列之自定义配置和路由的全部内容,更多相关PHP内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(92)

评论列表共有 0 条评论

立即
投稿
返回
顶部