PHP5 Setters Should Return $this

I think that as a convention, I will now have all setters return $this instead of null. I arrived at this decision from messing around with the Specification design pattern (“Domain Driven Design” by Eric Evans, pg. 224). When I was creating a chain of specifications in my Policy object, I ended up making a large number of Factory methods, one for each concrete Specification type. During one refactoring, I added an attribute with a setter for if this was a “normal” specification or just a “warning” specification (one that would log a normal error message if not satisfied, but still allow the policy to take place if other specifications on the chain were sufficient). A little more info on my experiment with the Specification pattern here.

Anyway, you end up with a factory method like this:

<?php

    private function fieldEquals($field, $value, $msg, $logdesc) {
        return new FieldEqualsSpecification($field, $value, $this->log, $msg, $logdesc);
    }

?>

And if you want a small variation of this method that sets the warning, you can do:

<?php

    private function fieldEqualsWarn($field, $value, $msg, $logdesc) {
        $ret = $this->fieldEquals($field, $value, $msg, $logdesc);
        $ret->setWarning();
        return $ret;
    }

?>

But, if you have the Specification::setWarning() method return $this instead of null (void) you can eliminate the temporary variable in the second Factory method and end up with this code:

<?php

    private function fieldEqualsWarn($field, $value, $msg, $logdesc) {
        return  $this->fieldEquals($field, $value, $msg, $logdesc)->setWarning();
    }

?>

Breaking it down the way the PHP parser does, you get:
$this->fieldEquals() returns an object
which we call the setWarning() method on
which returns an object that we return from this method

I’ll have to contemplate it a bit, but “When in doubt, return $this” may become a mantra for my PHP5 development 😉