How to restrict PHP traits to certain classes
php, traits
Solution
The best you can do is use `abstract` method definitions to impose requirements upon the exhibiting class:
trait ARCacheableTrait {
public function instantiate() {
parent::foo();
}
abstract public function foo();
}
That forces the exhibiting class to implement a method `foo`, so as to ensure that the trait can call it. However, there's no way to restrict a trait to be exhibited exclusively within a certain class hierarchy. If you want that, you probably want to implement a specific sub class of `ActiveRecord` which implements this specific `instantiate` behaviour instead of using a trait.
Problem
I have the following trait: ``` trait ARCacheableTrait { public function instantiate() { // this will need to call some ActiveRecord methods using parent:: } } ``` It's purpose is to override the `instantiate` method of `ActiveRecord` classes. What is the proper way to ensure that it's applied only over such classes? I'd want to throw an exception if someone tries to add it to classes that are not or do not extend `ActiveRecord` or even better, ensure type safety by throwing a compile time error...