28

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 ?

Alireza Amrollahi
  • 930
  • 3
  • 12
  • 27
Shankar Thiyagaraajan
  • 1,705
  • 4
  • 28
  • 46
  • 4
    Why reinvent the wheel? https://packagist.org/packages/symfony/var-dumper – Rajender Joshi Jan 16 '17 at 04:27
  • 2
    @RajenderJoshi Sometimes you want a rubber tire instead of one made from wood or stone. Laravel uses varDumper only for the formatting - the behaviour is _kind of_ different, because the execution is not stopped after dumping data. – Coloured Panda Jan 16 '17 at 07:10
  • @RajenderJoshi in my case, i need dd() as a static file, not as a Composer package, as the legacy application would otherwise break (as it would call autoloader several times) – Sliq Nov 11 '21 at 17:14

16 Answers16

40

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

symfony/var-dumper version >= 4.1:

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


symfony/var-dumper version <= 4.0:

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;
    }
 }
Coloured Panda
  • 3,293
  • 3
  • 20
  • 30
  • 1
    latest VarDumper versions already have dd function added by default. You don't have to manually create one. – M_R_K Feb 17 '21 at 13:04
23

I updated more functions and latest code of d functions below in debug functions package.

(Below answer is about 1 year ago.)

======================================

Below is my own code. It can work in plain PHP (no framework).

function d($data){
    if(is_null($data)){
        $str = "<i>NULL</i>";
    }elseif($data == ""){
        $str = "<i>Empty</i>";
    }elseif(is_array($data)){
        if(count($data) == 0){
            $str = "<i>Empty array.</i>";
        }else{
            $str = "<table style=\"border-bottom:0px solid #000;\" cellpadding=\"0\" cellspacing=\"0\">";
            foreach ($data as $key => $value) {
                $str .= "<tr><td style=\"background-color:#008B8B; color:#FFF;border:1px solid #000;\">" . $key . "</td><td style=\"border:1px solid #000;\">" . d($value) . "</td></tr>";
            }
            $str .= "</table>";
        }
    }elseif(is_resource($data)){
        while($arr = mysql_fetch_array($data)){
            $data_array[] = $arr;
        }
        $str = d($data_array);
    }elseif(is_object($data)){
        $str = d(get_object_vars($data));
    }elseif(is_bool($data)){
        $str = "<i>" . ($data ? "True" : "False") . "</i>";
    }else{
        $str = $data;
        $str = preg_replace("/\n/", "<br>\n", $str);
    }
    return $str;
}

function dnl($data){
    echo d($data) . "<br>\n";
}

function dd($data){
    echo dnl($data);
    exit;
}

function ddt($message = ""){
    echo "[" . date("Y/m/d H:i:s") . "]" . $message . "<br>\n";
}
Ngoc Nam
  • 537
  • 3
  • 13
6

For others who might be interested in Laravel like dd(), please check this repo -

https://github.com/wanfeiyy/laravel-dd

Rajitha Bandara
  • 743
  • 1
  • 10
  • 16
  • 2
    If you watch the source code of that library, turns out it's actually quite simple to replicate using the original Symphony components. All the logic seems to be in this file and it's quite simple to copy: https://github.com/wanfeiyy/laravel-dd/blob/master/src/Dd/Dumper.php – Fran Cano Jun 05 '19 at 10:33
5

The Laravel dd is actually a great function. However, the undergoing mechanism is var_dump and then die.

Example:

$arr = [1,2,3,4,5,6];
var_dump($arr);
die();
Arun Code
  • 1,548
  • 1
  • 13
  • 18
  • Yah, you are right. But what abt its schema. It won't elaborate entire array. Because in some cases, array may be too big. In that case we couldn't use that. But laravel do some stuff to minimise this issue by fold up. – Shankar Thiyagaraajan Jan 16 '17 at 10:56
  • you can set the depth that `var_dump()` will go to. I can't remember how (I think it might be in php.ini) – robertmain Jan 23 '18 at 16:28
5

composer require --dev symfony/var-dumper

<?php     
if (! function_exists('dd')) {
            /**
             * Dump the passed variables and end the script.
             *
             * @param  mixed
             * @return void
             */
            function dd()
            {
                array_map(function ($value) {
                    if (class_exists(Symfony\Component\VarDumper\Dumper\CliDumper::class)) {
                        $dumper = 'cli' === PHP_SAPI ?
                            new Symfony\Component\VarDumper\Dumper\CliDumper :
                            new Symfony\Component\VarDumper\Dumper\HtmlDumper;
                        $dumper->dump((new Symfony\Component\VarDumper\Cloner\VarCloner)->cloneVar($value));
                    } else {
                        var_dump($value);
                    }
                }, func_get_args());
                die(1);
            }
        }

?>
Abdo-Host
  • 2,470
  • 34
  • 33
3

You can bring in this namespace in your class use Illuminate\Support\Debug\Dumper; and then use it for your variables like this:

(new Dumper)->dump($myVariable);
Bitclaw
  • 813
  • 9
  • 8
2

I do it like this:

function dd($a){
    var_dump($a);
    exit;
}

I use it all the time. Even created a Snippet for it in Sublime.

I also use var_masterpiece Chrome extension to get a nice output, where I can expand and collapse the array keys, etc.

Lucas Bustamante
  • 15,821
  • 7
  • 92
  • 86
2

I do like this:

function dd($var){ 
    echo "<pre>";
    print_r($var);
    exit;
}
Husnain Aslam
  • 865
  • 1
  • 11
  • 28
2

it works like a charm.

function dd()
{
   array_map(function($x) { var_dump($x); }, func_get_args()); die;
}
Mehran
  • 175
  • 1
  • 10
1

Most of the time i work with laravel framework, when it came to debugging the dd() helper method become a very handful tool.

But recently i was requested to work on a symfony 3.4 project, at first i use dump($my_vars); die(); to dump and die my vars. But that became quickly very combersome. So i ended up by adding a dd() global helper method to the symfony 3.4 project, here is how:

Inside src/ folder i created Support/ folder, inside of the Support/ folder i created helpers.php file where i added my dump helper functions.

src/Support/helpers.php

if (!function_exists('dd')) {

    /**
     * Dump the passed variables and end the script.
     *
     * @return void
     */
    function dd() {

        $args = func_get_args();

        call_user_func_array('dump', $args);

        die(1);
    }
}

You may need to add the new file (helpers.php) to your composer.json file to be loaded for you automatically, like this:

composer.json

{
    ...

    "autoload": {
        "psr-4": {
            "App\\": "src/"
        },
        "files": [
            "src/Support/helpers.php"
        ]
    },

    ...
}
chebaby
  • 7,362
  • 50
  • 46
1

The @coloured-panda answer is not working anymore. Here is the updated code:

use Symfony\Component\VarDumper\VarDumper;

if (! function_exists('dd')) {
    /**
     * Dump the passed variables and end the script.
     *
     * @param  mixed  $vars
     * @return void
     */
    function dd(...$vars)
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: *');
        header('Access-Control-Allow-Headers: *');
        http_response_code(500);

        foreach ($vars as $v) {
            VarDumper::dump($v);
        }

        die(1);
    }
}
0

You can use the package mp091689/dump-die and then you can do:

dd($variable);

OR

dd($variable1, $variable2, ..);
luckyali444
  • 298
  • 3
  • 15
0

Here is the simplest solution:

if(!function_exists('dd'))
{
    function dd( $result )
    {
        echo '<pre>'; print_r($result); die();
    }
}
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
Abdalla A
  • 31
  • 3
0
if(!function_exists('dd')) { 
    function dd($arrayData, $exit=TRUE) {
        echo "<pre>"; print_r($arrayData);
        if($exit===TRUE) die();
    }
}
Ram Pukar
  • 1,583
  • 15
  • 17
0
if (!function_exists('dd')) {

    #[NoReturn] function dd(mixed $data):void
    {
        echo "<pre style='background:#1d1d1d; color: greenyellow; position:absolute; left: 0; top: 0; z-index: 9999999; width: 100%; height: 600px'>";
        print_r($data);
        echo '<pre>';
        die();
    }

}
0

I use the following one. Learned from Jeffrey Way:

function dd($data)
{
    echo "<pre>";
        var_dump($data);
    echo "</pre>";

    die();
}
Wakil Ahmed
  • 1,053
  • 1
  • 8
  • 16