search
HomeBackend DevelopmentPHP Tutorial使用VarDumper进行优雅的PHP调试

原文来自: https://jellybool.com/post/a-brand-new-way-to-test-php-with-symfony-va...

相信很多PHP开发者在写代码的时候都会经常用到var_dump()这个函数,很多人都会直接用类似die(var_dump($var))来查看一个变量或者一个实例到底是长什么样的,稍微有一些人可能还直接封装过:比如直接叫一个vdd()等,以便于自己在调试自己的代码的时候使用。这种方式一直陪伴着我走过了这么久的编程时光,以至于造成了对var_dump()出来的现实样式都有一点审美疲劳了:因为var_dump()出来的可以说是完全没有什么美感啊,至少对于像我们这些代码工作者来说:你竟然没有高亮!!不能接受。

相遇

然后之前苦于没有找到很好的解决方案,也就是一直这样忍受着过来了,直到昨天我发现了这货:

Symfony VarDumper

测试样式是长这样的:

我第一眼看到这个的时候就马上爱上这货了,忍不住要写点东西来分享一下:

先来说说Symfony VarDumper的优点,Symfony VarDumper不仅可以做到像var_dump()一样调试,而且可以做得更好,并不是只靠脸生活的:

  • 你可以轻松配置输出数据的格式:HTML 或者 命令行样式

  • 对于一些可能重复太多的数据,VarDumper智能过滤将其折叠起来,并且你可以很完美地看到你的数据的结构是什么样的,不清楚的话等下可以看下面的截图。

  • 每个打印出来的对象或变量都有特定的样式。

  • 安装使用之

    说了这么多之后,我们终于要来一睹庐山真面目了。首先是安装,最简单的方法就是直接使用composer安装,创建一个新的文件夹php/,我们来测试一下:

    cd php/composer require symfony/var-dumper

    再来创建一个index.php,将自动加载文件autoload.php包含进来:

    <?phprequire __DIR__.'/vendor/autoload.php';

    首先在index.php写一个简单的数组来测试一下:

    <?phprequire __DIR__.'/vendor/autoload.php';$var = array(    'a simple string' => 'in an array of 5 elements',    'a float' => 1.0,    'an integer' => 1,    'a boolean' => true,    'an empty array' => array(),);dump($var);

    出来的结果是这样的:

    有没有觉得很不错!这里还要说一点的是:如果你觉得Symfony VarDumper自带的样式不够美观,你可以直接到Dumper/HtmlDumper.php去修改你的自己的样式,比如你很喜欢github风,你完全可以自己在这个文件里面写你自己的css样式。

    上面对于数组的表现Symfony VarDumper貌似做得很完美,不仅给我们舒适的高亮,还很清晰的给了我们这个数组的结构。那么对于php中的stdObject,Symfony VarDumper的表现会是如何呢?我们来看看:

    class Test {    public $prop1 = 10;    private $prop2 = 20;    protected $prop3 = 30;    private $prop4 = 40;    public function __construct($value) {        $this->undefinedProp = $value;    }}$test = new Test(50);dump($test);

    出来的结果是这样的,注意它的高粱颜色有不一样了:

    这里可以看到:public就用 + 表示,private 就用 - 表示,而protected 就用 # 表示。不见如此,如果你仔细看图,你会看到当鼠标浮在对应的属性上面的时候,会有一个小小的提示框来提醒我们这个具体是什么,很完美啊。

    我们既然需要测试,那么在类中添加对应的方法呢,这个到底会给我们什么样的调试反馈呢?

    class Test {    public $methodOne;    protected $methodTwo;    public function __construct() {        $this->methodTwo = function() {            return 'I am method 2';        };    }    public function buildFunction() {        $this->methodThree = function() {            return 'I am method 3';        };    }    public function __call($method, $args)    {        if (isset($this->$method)) {            $func = $this->$method;            return call_user_func_array($func, $args);        }    }}$test = new Test();$methodOne = function() {    return 'I am method 1';};$test->methodOne = $methodOne;$test->buildFunction();$test->methodOne();dump($test);

    表现依然很惊艳:

    在上图中,你不仅可以很清晰地知道各个方法的类名是什么,也可以知道this代表的是什么,甚至还可以知道这个代码段是从第几行开始第几行结束的!666...

    最后

    可能很多同学看了这篇文章之后会觉得我们在自定义样式时直接改文件不太好,因为这个时候,如果你切换到其他的项目,你还是得重新再安装一次,难道还得再改一次?不是这样的,其实我推荐大家的做法是:全局安装Symfony VarDumper,这样不仅可以解决样式一次性问题,还可以让你在任何项目中使用Symfony VarDumper,安装方法如下:

    第一步,全局安装:

    composer global require symfony/var-dumper;

    第二:配置php.ini

    在php.ini中找到auto_prepend_file,然后写上你相对应的路径,比如像下面这样的:

     auto_prepend_file = ${HOME}/.composer/vendor/autoload.php 

    最后,更新composer

    直接命令行执行:

    composer global update

    到这里,你就可以配置好一个很优雅的调试界面了。反正我是很喜欢,不知道你是什么感受。

    Happy Hacking

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

    The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

    How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

    Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

    What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

    SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

    How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

    Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

    How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

    To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

    How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

    Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

    What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

    Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

    How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

    In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment