How to write own DD() function same as laravel?

Shankar Thiyagaraajan picture Shankar Thiyagaraajan · Jan 16, 2017 · Viewed 56.2k times · Source

I used laravel for a long time but currently I work with wordpress. I loved using the laravel's DD() function. But in wordpress I can only use these,

   print_r(),
   var_dump(),
   var_export()....

These all are just expand entire array or object. But I need laravel's expand and close mechanism for handling array and object. I use the following as general dd need,

if (!function_exists('dd')) {
 function dd()
  {
      echo '<pre>';
      array_map(function($x) {var_dump($x);}, func_get_args());
      die;
   }
 }

It works well, but I need a styled and organised form of listing.

Is it possible ?

Answer

Coloured Panda picture Coloured Panda · Jan 16, 2017

Laravel's dd uses symfony's VarDump component. It provides a globally available dump function which formats the output. The only difference is that it won`t "die" after the dump, you'll have to do that manually - but in most cases that isn't even something you'd want.

  1. Run composer global require symfony/var-dumper (assuming you have composer in your wordpress project)
  2. Add auto_prepend_file = ${HOME}/.composer/vendor/autoload.php to your php.ini file;
  3. From time to time, run composer global update symfony/var-dumper to have the latest bug fixes.

Here is the documentation for the VarDumper component. https://symfony.com/doc/current/components/var_dumper.html

Before var-dumpr version 4.1:

Declare a dd function, dumping all arguments and stopping the process:

if (!function_exists('dd')) {
    function dd()
    {
        foreach (func_get_args() as $x) {
            dump($x);
        }
        die;
    }
 }

After var-dump version 4.1:

Since var-dumper version 4.1, dd() is already declared. Loading the library is enough.