user2816626
user2816626

Reputation: 83

Using Traits to cover implementation requirements of Interfaces

Recently i came across multiple articles that are implying using Traits to cover implementation of Interfaces. Example:

interface ArticleInterface
{
    /**
     * @return mixed
     */
    public function getTitle();
}

trait ArticleTrait
{
   /**
     * @return string
     */
    public function getTitle()
    {
        return "article_title";
    }
}

abstract class AbstractArticle implements ArticleInterface
{
    use ArticleTrait;
}

Some even think that Traits implementing Interfaces should be available in PHP core.

Therefore i am trying to get a proper response on a question if this design pattern should be followed ? If yes, should PHPDoc description be written in both interface and trait (meaning it will be duplicated) ? Any other details that i should take notice of when using this design ?

Upvotes: 1

Views: 328

Answers (1)

bishop
bishop

Reputation: 39394

Traits provide for compiler-assisted copy-and-paste. They are a form of code re-use. While class inheritance gives you code re-use vertically (child classes share code defined in their parents), traits give you code re-use horizontally: interface-sharing classes can use code defined in the trait.

So, yes, if you have multiple siblings sharing the same interface and implementation, then you may use traits to reduce code duplication. But, no, if you have only one class implementing an interface - as in your example - then traits add undeserved complexity.

I'd like to add one important point: traits don't, themselves, store state. Any member variable in the trait will ultimately be stored in the object consuming the trait. If you have some state information that should be considered "private" to the trait (and therefore unavailable in the object), then don't use traits for re-use. Instead, use service delegates.

Upvotes: 3

Related Questions