Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Debugging collection chains

Original – by Freek Van der Herten – 2 minute read

A couple of weeks ago I published a blog post on how you can easily debug collections using a dd macro. Meanwhile my company released a package that contains that macro. In this post I'd like to introduce a new dump macro, recently introduced in the package, that makes debugging collection chain even easier.

Here's what the dump macro itself looks like.

Collection::macro('dump', function () {
    Collection::make(func_get_args())
        ->push($this)
        ->each(function ($item) {
            (new Dumper)->dump($item);
        });
    return $this;
});

So what the macro basically does is dumping any argument you give it to the screen together with the collection itself. The entire collection is returned, so you can further chain it. Sounds a little abstract, no? Easier said: this macro can be used to dump all the steps in your collection chain to the screen.

Let's see it in action. Take a look this collection chain:

collect([1,2,3])
    ->dump('original collection')

    ->map(function(int $number) {
        return $number * 2;
    })
    ->dump('multiplied by two')

    ->filter(function(int $number) {
        return $number > 3;
    })
    ->dump('filtered higher than three')

    ->dd();

Executing that chain results in this being displayed on the screen.

dump output

Displaying every transformation in the chain will make it much easier to find a potential bug. Hope you like it!

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

What are your thoughts on "Debugging collection chains"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.