SwooleDistributed 框架如何让调试信息展示的 web 界面上

1,000 阅读1分钟
原文链接: blog.hainuo.info

如题我们今天探讨的是如何将 debug 信息输出在页面上,面向的对象是习惯了 php-fpm 和 Apache 方式的用户。原因很简单,因为很多用户都喜欢在页面设置断点,即 使用 var_dump() 方法来调试 PHP 程序。下面我们来进行两种方式的尝试。

0x01 通过模板方式

本方式需要建立两个模板,并使用 Plates 的 Layout 布局。

  1. 首先在 app 目录下建立 Views 目录,这个目录就是框架默认的模板目录了。
  2. 然后在 Views 目录下创建 Layout 目录,这个目的是将所有的基础模板都放在这里面,清楚的表明这是Plates 模板引擎的 Layout 方式基础模板存放地址。
  3. 然后创建文件Layout/template.php。内容如下
    < !DOCTYPE html>
     < html lang="en">
     < head>
         
         <?= $this->e($title) ?>
     <\/head>
     <\body>
     section('content') ?>
     
    ' . $value . ''; echo $value; } ?>
    <\/body> <\/html>
    lass="pun">>
  • 在Views下创建文件error_404.php
    ,内容如下
     layout('app::Layout/template', ['title' => '404 Page Not Found app','dumps'=>$dumps]) ?>
     

    e($controller)?>

    e($message)?>
    app 目录的 error_404
  • 然后我们来创建一个新的控制器,base.php
    
    
    
    namespace app\Controllers;
     use Server\CoreBase\Controller;
     class base extends Controller
     {
         public function display($views, $data = [])
         {
             if (empty($views)) {
                 $views = 'app::error_404';
                 $array = [
                     'controller' => 'TestController\html_test',
                     'message'    => '页面不存在!',
                 ];
             } else {
                 $array = [
                     'dumps' => [
                         'ddd' => 3434,
                     ],
                 ];
             }
             $template = $this->loader->view($views);
             $data = [
                 'dumps' => $_SERVER,
             ];
             $array = array_merge($array, $data);
             $this->http_output->response->end($template->render($array));
         }
     }
  • 我们新创建一个新的控制器 Login.php
    namespace app\Controllers;
     class Login extends base{
         public function http_index(){
             $this->display(null,[
                 'dumps'=>[
                     'a'=>2134234
                 ]
             ]);
         }
     }
  • 运行服务器 php start_swoole_server.php start
  • 访问 http://localhost:8081/Login/index 可得到这样的界面
  • 第一种解决方法搞定
  • 0x02 第二种解决方法 使用 swoole_http_response 的 write() 和 end() 方法

    1. 修改 base.php
      /**
            * 输出信息
            */
           public function dump()
           {
               $arr = func_get_args();
               foreach ($arr as $value) {
                   $value = var_export($value, true);
                   $value = 'pre' . $value . '/pre';
                   $this->http_output->response->write($value);
               }
           }
       }
    2. 修改 Login.php
             $this->dump($this->config->get('server.set'));
               $this->display(null, [
                   'dumps' => [
                       'a' => 2134234,
                   ],
               ]);
    3. 修改后访问效果如下图所示

      0x03 总结

    至此解决我们的问题。主要是做了个封装通过模板方式和 write方式实现两种解决方案