Yii2: Dump and die Laravel style.

Created on 19 Feb 2015  路  39Comments  路  Source: yiisoft/yii2

In Yii developers often write

var_dump($var);
die();

while debugging. It is exhausting. In Laravel we can simply write

dd($var);

Why not to do the same thing in Yii?

docs

Most helpful comment

@klimov-paul

It does not make sense.

Ofcourse it make sence. From team development point of view. Having official shortcuts much more better than having personal home grown shortcuts per team.

All 39 comments

Use VarDumper::dump().
You can wrap it in whatever you want if you need it.

@klimov-paul I know it, but write

use yii\helpers\VarDumper;
VarDumper::dump($var);

or even

yii\helpers\VarDumper::dump($var);

is also overkill.

Much more characters than in Laravel's dd().
http://laravel.com/docs/4.2/helpers#miscellaneous

Surely I forced to wrap yii\helpers\VarDumper::dump($var). Thought, a lot of developers do the same. May be it will be better to add the alias to Yii's core like it's done in Laravel?

Who does prevent you to declare your own function?

function dd($var)
{
    \yii\helpers\VarDumper::dump($var);
    exit();
}

Name it as you like and use for your good.
Where is "overkill" here?

  1. Create functions.php.
  2. Include it just before run() in index.php.
  3. Define hh() there:
function hh($data)
{
    yii\helpers\VarDumper::dump($data, 10, true);
    Yii::$app->end();
}

@klimov-paul @samdark As I wrote before, I already do it. There is no problem to write a function for me. I want to have it out of the box like in Laravel. Just proposed a feature, that can be useful for many of Yii's users.

It does not make sense.
It is better for developers to declare this function on thier own, with the name they like and any further adjustments.

It could be reflected in documentation section, like: Adding global helper functions. And just to have couple of examples of such cases.

Yep. I'll handle docs.

@klimov-paul

It does not make sense.

Ofcourse it make sence. From team development point of view. Having official shortcuts much more better than having personal home grown shortcuts per team.

-1
I tend to agree to klimov-paul. At least I don't agree to @samdarks suggestion with an extra functions.php file. Not everyone is using the official base or advanced app templates, so this solution would not work for everyone (leading to confusion). If done right, this should be part of YiiBase.php or at least be included from there.

EDIT: And if implemented I'd also vote for a more verbose name like debug() or dump().

may be need remove namespace for VarDumper ?

+1 (of course). I havent seen anything more ugly than the function VarDumper::dump() apart from Codeception having \Codeception\Util\Debug::debug()

The whole thing about dumping is fast debugging (the faster the process, the faster the bug found / solution). Having to remember + type something like 'VarDumper::dump()' is not optimal. I even have to get it from my cheatsheet. So dd() will save an significant amount of time

It does not make sense.

how could something like a standard + short cut not make sense. Its standardization and optimization ? @akireikin is showing a use case with is implemented in another big framework.

From team development point of view. Having official shortcuts much more better than having personal home grown shortcuts per team.

exactly

Another handy usecase is pre():

function pre($mixed){
echo '<pre>';
print_r($mixed);
echo '</pre>';
}

giving wonderful output like:

(
    [0] => foo
    [bar] => boo
)

@mikehaertl I'm not for adding it to the framework app templates, I'm for documenting the possibility of doing it yourself.

Adding global methods in core framework is not a best solution because there could be conflicts in names with additional extensions.

If introduce shortcuts officialy it should be done for every helper, for every method... Conflicts can be solved by additinal checking:

if (!function_exists('url_to')) {
    function url_to(...) {
        \yii\helpers\Url::to(...);
    }
}

This is how this works in Laravel. And ofcourse it much more usable than import \yii\helpers\Url at top of view (which is pain) and than write Url::to(). Just simple example for simple helper. We have lots of helpers with lots of methods. Little pain become heavy pain. To be honest very often when i write inside view something like ArrayHelper::something() i cleanly understand that something WRONG with Yii at this point.

documenting the possibility of doing it yourself

Will lead to next generation of "the inventors of the wheel". From companies point of view its better to have official helpers or do not have it at all.

If introduce shortcuts officialy it should be done for every helper, for every method

Its not so bad Idea to shortcut a top X of the most used functions.

@creocoder checks with function_exists is a good idea.
What about naming convention? Helper functions naming should be standartized as other functions (camelCase)?

a naming convention related to Yii software wouldnt be so bad either:

yTag() -> \yii\helpers\Html::tag()
yUrl() -> \yii\helpersUrl::to()
yDump() -> \yii\helpers\Vardumper::dump()

Benefits:

  • super short
  • easy to remember
  • functions as an alias (for future naming changes)
  • still has some indication to Yii because of its Y
  • not likely to interfere with other functions because of the y-prefix

What about naming convention? Helper functions naming should be standartized as other functions (camelCase)?

CamelCase for methods. For function there is already naming conventions inside php itself and its underscore. Also such helpers is natural for php. For example: date_create_from_format() as helper for DateTime::createFromFormat(). Laravel go php language way by introducing shortcuts for its helpers.

I'm not for adding it to the framework app templates, I'm for documenting the possibility of doing it yourself.

@samdark I see now. Makes perfect sense to me. The discussion here already shows, that it's hard to find a consensus. So IMO this should really be solved on a per-team basis and not be part of the framework itself.

@creocoder Thats a good point.
I've found this listing of naming conventions of other frameworks & CMS.

Here is a PHP naming convention
Note section: User Functions/Methods Naming Conventions

Function names for user-level functions should be enclosed with in
the PHP_FUNCTION() macro. They should be in lowercase, with words
underscore delimited, with care taken to minimize the letter count.
Abbreviations should not be used when they greatly decrease the
readability of the function name itself::

Good:
'mcrypt_enc_self_test'
'mysql_list_fields'

perfect

@akireikin that is already possible with a extension 'Kint', it is the same using on Laravel.

Just add it to your composer. For further informations access: http://raveren.github.io/kint/

@marcoantoniooliveira nice extension. Thank you.

Imho this feature should be include in core framework, it encourage clean code and it will make developers happy :)

For anyone wanting a nice var-dumper, I suggest including the same as in Laravel - symfony var dumper (http://symfony.com/doc/current/components/var_dumper/introduction.html)

  1. Add composer dependency: "symfony/var-dumper": "~2.6"
  2. Define dd() function:
function dd()
    {
        array_map(function ($x){
            $dumper = 'cli' === PHP_SAPI ? new CliDumper : new HtmlDumper;
            $dumper->dump((new VarCloner)->cloneVar($x));
        }, func_get_args());
       die;
    }

...and enjoy ;)

It's just a pitty, that Yii's philosophy isn't about making coding fun, easy, convenient, Laravel is so much better at this.

Can be done w/o using external components:

function dd()
{
    array_map(function ($x){
        echo \yii\helpers\VarDumper::dump($x, 10, true);    
    }, func_get_args());
}

Just to think about: maybe we should introduce Yii::dump()? It can cover this pupular demand and will have short enough name.

@samdark Symfony dumper is more pleasant to use - expandable, etc.

If I wan't to browse a model, view attributes, etc, dump a model instance:

Yii dumper: https://ziedlejas.lv/screenshots/img.2015.06.04.OvKENP.jpg (couldn't fit in the screen)
Symfony dumper: https://ziedlejas.lv/screenshots/img.2015.06.04.wMDl8V.png

@briedis There is an error if function only defined, but no libraries used.

Class 'HtmlDumper' not found

Before function dd() add

use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;

Or write something like this:

function dd()
{
    array_map(function ($x){
        $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($x));
    }, func_get_args());
    die;
}

@a-komarev

Sorry, yeah, I had them imported, and forgot to copy that part.

To avoid already defined function, one can use function_exists function.

if(!function_exists('dd')){
   function dd(){
      ...
   }
}

I agree this functionality to be covered by an external library like ie. Kint http://raveren.github.io/kint/

I think it's better to leave it to developers. Not going to suggest and "official" way of achieving it.

@briedis thanks.

For anyone who wants the same styles as in Laravel var-dumper, just replace $styles array in Symfony\Component\VarDumper\Dumper\HtmlDumper class with the following:

protected $styles = array(
    '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',
);

If you're a sublime user and want a more consistent, framework-agnostic experience: https://gist.github.com/gr33k01/4d8ee334f38db027acc3360b2c3e988f

Someone could create an extension for this and developers could place it into require-dev 馃樅

@schmunk42 there is composer require larapack/dd 1.*

Was this page helpful?
0 / 5 - 0 ratings