msvrtan's blog

Trait pattern in PHP

Trait pattern description

Instead of trying to explain traits myself I will use PHP manual and wikipedia descriptions:</p>


In computer programming, a trait is a collection of methods, used as a "simple conceptual model for structuring object oriented programs"

PHP manual:

"A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance. "

SessionSingleton example

I wrote a short blog post on singleton pattern and will use SessionSingleton example here to describe why we needed traits so badly (they are one of features that came with PHP 5.4).</p>

As you can see in SessionSingleton class there are ~10 lines of code (without comments) needed for implementing Singleton pattern so why would we copy them around every time we want to build a singleton class? Lets move those lines of code into separate class that all singleton classes will extend. This means that our SessionSingleton class is now somewhat cleaner and easier to maintain since any bugs detected on Singleton implementation can be fixed on one place instead of using search-and-destroy bugfixing.

The next step .. traits

As you can see now we still have get(),set() & add() methods defined that are probably used all around already and are being copyed back and forth. We shouldnt move it into base singleton class since all other singletons will not have any use of it and on the other hand if we want some other classes to use it we would give them Singleton availability which we dont want. Since PHP doesn’t support multiple inheritance or mixins we have 2 solutions:</p>

1) Copy paste them around, which is boooring :)
2) Use traits

So we have moved Singleton and Values (this is how I decided to call those pesky get,set and add methods collection) into their respective traits. New session singleton class now implements only actual logic needed, setting up $_SESSION data into $arrValues and looks like this:

class SessionSingleton

use SingletonTrait, ValuesTrait;

protected function __construct()

$this->arrValues = $_SESSION;
This way we can do DRY much easier which will help us make better code (all of those copy pasting usually produces forgetting something, copying unwanted or not needed parts of code), easier to maintain (bugfix in implementation can be fixed on one place) and help us build new features with much less pain.

NOTE: this code is only an example of implementation for session singleton used only for explaining singleton and trait patterns.