Null Object Pattern in Laravel
Tihomir Tonov shows us how to use a design pattern called Null Object Pattern to deal with null responses.
The Null Object Pattern is a design pattern, where some function/method returns an object or literal, that should act as a “null” version of the expected one. You can read more on Wikipedia about it. A simple example might be a function, that should return an array of items, which you want to filter, map over its items or just pass it into foreach. But what happens when there are no items to return? You might return null, but now you need to check, every time before performing, that foreach loop. The null object alternative would be to return an empty array and skip the check, just run the foreach.
This post is submitted by one of our members. You may submit a new post here.