咱们曾经开发实现,但咱们还需求更多。比方自界说设置装备摆设以及路由。
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编程从入门到通晓
以上就是PHP DIY系列之自界说设置装备摆设以及路由的具体内容,更多请存眷资源魔其它相干文章!
标签: php 自定义配置 路由 php开发教程 php开发资料 php开发自学
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!