PHP: Executing a method conditionally

We’re going back to using when and unless

Italo Baeza Cabrera
2 min readJul 13, 2020

When I was coding something, I needed to execute a method in a class when a value was evaluated to truthy.

Practically speaking, the Transport received a package, and depending on the conditions of the package, it would handle it differently. Also, if the weather was dangerous (snowing, tornados or Godzilla), it should notify the user for possible delays.

The code is not that pretty to read, at least for me.

if ($package->isBig()) {
$transport->useVan();
}
if ($package->isFragile()) {
$transport->handleWithCaution();
}
if ($weather->isDangerous()) {
$transport->notifyPossibleDelay();
}
return $transport->deliver();

While this is lexically correct and understandable, I decided to go the extra mile and try to one-line everything, not using a callable as my previous article allowed to.

Instead, call the next method depending on the result of the previous method value.

$transport->when($package->isBig())->useVan()->deliver();

Welp, I can do that.

Catching the next method, programatically

The only way to do this is to trap the object we’re using into another, with the value that is evaluated.

To trap this, we can simply use an empty “Container” object that will hold the object, and the value being evaluated. The next method will be executed on this object. Since it will be catched by the __call magic method, we can pass the method name and its arguments to the underlying target if it should or not depending on the value we pushed before.

The “container” class looks like this:

And the way we can call it in any class is by creating a method called when(), which will instance a new Container object containing the target object.

public function when($value)
{
return new Container($this, $value);
}

We can do amazing things with this snippet, making large lines into one, without growing methods into unscrupulous text walls full of if chains that break the flow of a class call.

Some may want to use the old way, and it’s okay because they may have been accustomed to the old way, but be wary that large methods with dozens of lines adds complexity to read, and some people are not okay with that (like me), especially when you’re in charge of writing and maintaining it.

You can find this trait and other helpers in my Laratraits package. Give it a chance if you find something useful to use in your project.

--

--

Italo Baeza Cabrera

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor. https://italobc.com