1. 輔助函式 dd()

ZouZhipeng發表於2021-02-23

新建一個空專案,安裝擴充套件包

composer require symfony/var-dumper

這樣一來就可以使用 dump() 了。不過還不夠,我們還要把 dd() 的程式碼放進來。

準備 dd()

找個地方複製以下程式碼 (helpers/laravel_helper.php )

<?php

# install symfony/var-dump to your project
# composer require symfony/var-dumper

// use namespace
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\Dumper\HtmlDumper as SymfonyHtmlDumper;

/**
 * Class HtmlDumper
 */
class HtmlDumper extends SymfonyHtmlDumper
{
    /**
     * Colour definitions for output.
     *
     * @var array
     */
    protected $styles = [
        'default' => 'background-color:#fff; color:#222; line-height:1.2em; font-weight:normal; font:12px Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:100000',
        'num' => 'color:#a71d5d',
        'const' => 'color:#795da3',
        'str' => 'color:#df5000',
        'cchr' => 'color:#222',
        'note' => 'color:#a71d5d',
        'ref' => 'color:#a0a0a0',
        'public' => 'color:#795da3',
        'protected' => 'color:#795da3',
        'private' => 'color:#795da3',
        'meta' => 'color:#b729d9',
        'key' => 'color:#df5000',
        'index' => 'color:#a71d5d',
    ];
}

/**
 * Class Dumper
 */
class Dumper
{
    /**
     * Dump a value with elegance.
     *
     * @param  mixed  $value
     * @return void
     */
    public function dump($value)
    {
        if (class_exists(CliDumper::class)) {
            $dumper = 'cli' === PHP_SAPI ? new CliDumper : new HtmlDumper;
            $dumper->dump((new VarCloner)->cloneVar($value));
        } else {
            var_dump($value);
        }
    }
}

if (!function_exists('dd')) {
    /**
     * Dump the passed variables and end the script.
     *
     * @param  mixed
     * @return void
     */
    function dd(...$args)
    {
        foreach ($args as $x) {
            (new Dumper)->dump($x);
        }
        die(1);
    }
}

if (!function_exists('dda')) {
    /**
     * Dump the passed array variables and end the script.
     *
     * @param  mixed
     * @return void
     */
    function dda(...$args)
    {
        foreach ($args as $x) {
            (new Dumper)->dump($x->toArray());
        }
        die(1);
    }
}

自動載入

composer.json 檔案新增以下內容

{
  .
  .
  .
  "autoload": {
    "files": [
      "helpers/laravel_helpers.php"
    ]
  }
}

最後更新一下,就可以 dd 用起來了!

composer dump-autoload (composer du)

使用示例 index/dd.php

<?php

require_once __DIR__ . '/../vendor/autoload.php';

dd($_SERVER);

命令列開啟服務 php -S localhost:8000 並訪問 http://localhost:8000/index/dd.php 即可。

專案目錄結構

.
├── composer.json
├── composer.lock
├── config
├── helpers
│   └── laravel_helpers.php
├── index
│   └── dd.php
├── src
└── vendor
    ├── autoload.php
    .
    .
    .

參考 致謝

  1. PHP 全域性使用 Laravel 輔助函式 dd
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章