BlogInversion Of Control (IOC) Simplified

4th February 2020

Imagine, for instance, that you need to write a function to get all users, you'd probably write something like this...

public function getUsers(): UserCollection
{
    return User::get();
}

And call it like this...

$users = getUsers(); // gets all users

This works nicely so, being a clean, DRY developer, you reuse it all over the place. Then a new requirement comes in, "can you limit users to active only on the listing page, please?"

The traditional response to this might be to add a flag defaulted to false to ensure older use cases aren't affected...

public function getUsers(bool $activeOnly = false): UserCollection
{
    $query = User::query();

    if($activeOnly){
        $query->whereActive();
    }

    return $query->get();
}

There are now three ways in which to call your clean function...

$users = getUsers(); // gets all users
$users = getUsers(false); // gets all users
$users = getUsers(true); // gets all active users

And now we have a lump of unclean logic that is called all over the place adding new complexities and consequences for each. Add a few more flags and you've built an unsupportable, untestable monstrosity.

This is the problem that IOC seeks to fix. IOC gives the code calling the method some control over the logic...

So, instead of a flag we add a closure to the function which we can us to pass in whatever additional logic we like...

public function getUsers(Closure $filterFunction = null): UserCollection
{
    $query = User::query();

    if(is_callable($filterFunction)){
        $filterFunction($query);
    }

    return $query->get();
}

We can now pass in our own function to filter the query without affecting the underlying logic of the original function, no flags necessary...

$users = getUsers(function(Builder $query){
    $query->whereActive();
}); // gets all active users

...or...

$activeUserFilter = function(Builder $query){
    $query->whereActive();
};

$users = getUsers($activeUserFilter); // gets all active users

Ands how IOC works.

Hope you find this useful!

Let's Talk