Are interface methods informed via __call?

I have an interface that announces the need to implement methods such as find, findOrFail, etc., mostly the eloquent Laravel methods.

I declare these methods in the interface because not everything that implements the interface will be eloquent, so I declare them in the interface, so my application always knows that the methods will be there.

What I want to know, in addition to the fact that in models there are a bunch of methods like public function find($id){return parent::find($id)} that do extend the eloquent model, there is an easy way to tell the interface that the method is processed through __call ?

+6
source share
2 answers

Although the question of the cleanliness of such a design may be more complex, you can do something similar to this using a trait that implements interface methods:

 interface FindableContract { public function find($id); } trait MagicFindableTrait { public function find($id) { return static::__call(__FUNCTION__, func_get_args()); } } class MagicalParent { public function __call($method, $args) { if ($method == 'find') { return "User " . $args[0] . " is a witch! May we burn her?!"; } } } class User extends MagicalParent implements FindableContract { use FindableTrait; } class NonmagicalUser implements FindableContract { public function find($id) { return "User $id was found to be nonmagical. Let burn him anyway."; } } print (new User)->find(123); print (new NonmagicalUser)->find(321); 
+4
source

No, that will not work. While __call() really good for the dynamic coding style, the disadvantage is that you cannot force dynamic method signatures in the interface, and you will not get automatic documentation for it.

But I think that if you are at the point where you want to create an interface for these methods, you no longer need to use __call() . I would just have hardcode methods.

+3
source

Source: https://habr.com/ru/post/947963/


All Articles