Using Traits and Interfaces
It is considered a best practice to make use of interfaces as a means of establishing the classification of a set of classes, and to guarantee the existence of certain methods. Traits and Interfaces often work together, and are an important aspect of implementation. Wherever you have a frequently used Interface that defines a method where the code does not change (such as a setter or getter), it is useful to also define a Trait that contains the actual code implementation.
How to do it...
- For this example, we will use
ConnectionAwareInterface
, first presented in Chapter 4, Working with PHP Object-Oriented Programming. This interface defines asetConnection()
method that sets a$connection
property. Two classes in theApplication\Generic
namespace,CountryList
andCustomerList
, contain redundant code, which matches the method defined in the interface. - Here is what
CountryList
looks like before the change:class CountryList { protected $connection; protected ...