How to avoid large function signatures by using pending objects

Freek is developing Mailcoach to send out e-mail campaigns. Along with the development of the package he’s recording a video series on how he has created it. In this video he talks about using “pending objects” to make the API more readable.

In this video I demonstrate how to you can create a fluent API by using pending objects. We’ll take a look at how subscribers can be created in Mailcoach. As a bonus I explain how jobs are dispatched using a pending object in Laravel.

// Without pending objects
// ~> What do all these params mean?! 🤔
Subscriber::createWithEmail($email, $attributes, null, true, false, $myList);

// With pending objects
// ~> So readable. Much amaze. Wow.
Subscriber::createWithEmail($email)
  ->withAttributes($attributes)
  ->skipConfirmation()
  ->subscribeToList($myList);

Whilst the implementation is Laravel-specific, it can be applied to any (PHP) project. I especially like the trick where PHP’s __destruct() magic function is leveraged to combine functions with pending objects.

How to avoid large function signatures by using pending objects →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.