Aug 22, 2017

What are Traits?

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

A Trait is simply a group of methods that you want include within another class. A Trait, like an abstract class, cannot be instantiated on it’s own.
 An example of a Trait could be:
trait Sharable {
 
  public function share($item)
  {
    return 'share this item';
  }
 
You could then include this Trait within other classes like this:
class Post {
 
  use Sharable;
 
}
 
class Comment {
 
  use Sharable;
 
}
 
 

How are Traits different to Abstract classes?

A Trait is different to an Abstract class (What are Abstract classes?) because they do not rely on inheritance.
Imagine if the Post and the Comment class had to inherit from a AbstractSocial class. We are most likely going to want to do more than just share posts and comments on social media websites, so we’ll probably end up with a complicated inheritance tree like this:
?



class AbstractValidate extends AbstractCache {}
class AbstractSocial extends AbstractValidate {}
class Post extends AbstractSocial {}
 

How are Traits different to Interfaces?

Traits kind of look a lot like Interfaces. Both Traits and interfaces are usually simple, concise and not much use without an actual implemented class. However the difference between the two is important.
An interface is a contract that says “this object is able to do this thing”, whereas a Trait is giving the object the ability to do the thing.
For example:

// Interface
interface Sociable {
 
  public function like();
  public function share();
 
}
 
// Trait
trait Sharable {
 
  public function share($item)
  {
    // share this item
  }
 
}
 
// Class
class Post implements Sociable {
 
  use Sharable;
 
  public function like()
  {
    //
  }
 
}

What are the benefits of Traits?

The benefit of using Traits is that you reduce code duplication whilst preventing complicated class inheritance that might not make sense within the context of your application.
This allows you to define simple Traits that are clear and concise and then mix in that functionality where appropriate.
 

No comments: