Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict PHP traits to certain classes

Tags:

php

traits

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...

like image 743
ddinchev Avatar asked Jul 13 '14 11:07

ddinchev


1 Answers

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.

like image 175
deceze Avatar answered Oct 29 '22 09:10

deceze