PHP DIY系列之自定义配置和路由

coldplay.xixi
풀어 주다: 2023-04-09 07:04:02
앞으로
2736명이 탐색했습니다.

PHP DIY系列之自定义配置和路由


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

app文件夹下新建Config.php

 false,
    'route' => [
        '' => 'demo/welcome',
        'test' => 'demo/test',
    ],];
로그인 후 복사

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

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);
    ...省略代码
로그인 후 복사

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

image

image

这里虽然有自定义路由,但是我们有时候需要禁止默认路由,所以我们不妨增加配置参数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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:learnku.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!