Reputation: 18741
I have an application with many classes in my Model, and each class has many properties.
Most of these classes share some properties, but in such a way that creating a class hierarchy using only single inheritance is not really suitable.
So I started creating some Traits containing only properties, without methods, such as:
trait Dateable {
protected $strat_date;
protected $end_date;
}
trait Featurable {
protected $image;
protected $description;
}
trait Buyable {
protected $price;
protected $buy_link;
}
etc... And then I define my classes like:
class Film {
use Featurable;
// some own properties...
}
class Showing {
use Dateable, Bookable;
// some own properties...
}
class Course {
use Featurable, Dateable, Bookable;
// some own properties...
}
This allows me to have a more organised model of classes, but I was wondering if this is a correct use of Traits because I can't find any examples of this...
Is not there any reason (e.g., performance) to avoid doing this?
Upvotes: 4
Views: 1487
Reputation: 1052
It's incorrect in terms of OOP, because pure OOP suggests that you encapsulate everything possible. In general words, you should not have any public properties. All object's data should be accessible only by object's methods.
In your example, you have protected
everywhere, but that is still a little bit incorrect, since it makes your code coupled on that trait meaning that you might get problems if you will try to disable it.
But if you will add getter-setter, then you are OK.
In fact, making those getters and setters abstract will ensure that your objects will be trully "Dateable, Featureable, Bookable, etc.".
A little bit better example would be trait called jsonParsable
that has abstract function toJson()
. Each class probably will have his own rules for returning JSON represenation, so it is good to make this trait abstract.
Upvotes: 2