Object-oriented – Avoiding boilerplate in PHP classes

clean codecode-qualitycoding-styleobject-orientedPHP

I am working on a PHP code and as it grows getting more and more tired of repeating the same standard pattern again and again and again:

class BolerPlate
{
    protected $property1;
    protected $property2;
    ...

    public function __construct ($property1, $property2, ...)
    {
        $this->property1 = $property1;
        $this->property2 = $property2;
        ...
    }
}

So I am re-typing here each property name 4 (!) times just to get the standard setup! In each class! It doesn't look elegant nor DRY to me. And re-typing the same names creates more bug opportunities.

I wonder if there is any more elegant way or best practices to get the same setup with a code easier on the eyes 🙂

EDIT. What I have in mind is some sort of factory method where I can supply the list of properties only once each. Or using variable variables and iterate over all properties?

Best Answer

In short: Traits might be the feature that you look for.

A trait is PHP 5.4’s solution to the lack of multiple inheritance in the language and a way to avoid hierarchical inheritance chains. Another way to think of it is that including traits in your classes is a clean way to keep your code dry without breaking good design principles.

An even more simple way to think about it is: Hey, all that boiler plate code that you copied and pasted everywhere but now you want to change something? well replace it with a trait and call it a day.

Here you are examples and good post on this topic.

Related Topic