Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
Well, assume we're having a User and Admin classes, which are required to use some methods with the same functionality. We'll look on how do we achieve this using both Interfaces and Traits.
If you're not familiar with the concepts of Traits and Interfaces in PHP, you can check on them from the below links:
Well, assume we're having a User and Admin classes, which are required to use some methods with the same functionality. We'll look on how do we achieve this using both Interfaces and Traits.
interface AuthenticatableInterface {
public function getPassword();
public function setPassword($password);
}
class User implements AuthenticatableInterface {
public function getPassword( ) {
// TODO: Implement getPassword() method.
}
public function setPassword( $password ) {
// TODO: Implement setPassword() method.
}
}
class Admin implements AuthenticatableInterface {
public function getPassword( ) {
// TODO: Implement getPassword() method.
}
public function setPassword( $password ) {
// TODO: Implement setPassword() method.
}
}trait Authenticatable {
public function getPassword( ) {
// TODO: Implement getPassword() method.
}
public function setPassword( $password ) {
// TODO: Implement setPassword() method.
}
}
class Admin implements AuthenticatableInterface {
use Authenticatable;
}
class User implements AuthenticatableInterface {
use Authenticatable;
}Well you can clearly see, using Traits can seriously DRY up your code and let you re-use & share methods within classes. Interfaces on the other hands are usable if you are required to use all of the methods in your class.
The above example is inspired by Laravel code-base. If you're familiar with Laravel, you can see how Taylor Otwell uses the combinations of Interfaces and Traits to clean up the code.
For this article, we've a bit of a task for you to explore Laravel files and directories to see how its working out. This will surely help you to understand the concept of Interfaces and Traits.
If you've any suggestions or feedback, do write us in the comment section below. You can also follow us on Twitter.
Related Readings