通过__call实现通知接口方法? [英] informing interface methods are implemented via __call?
问题描述
我有一个接口,声明了实现需要的方法,比如find,findOrFail等,基本上是Laravel雄辩的方法。
I have an interface that declares the implementation needs methods such as find, findOrFail etc, basically Laravel eloquent methods.
我在接口中声明了这些方法,因为实现接口的所有方法都不会扩展,所以我在接口中声明它们,所以我的应用程序总是知道方法将是那里。
I declare these methods in the interface because not everything that implements the interface will extend eloquent so I declare them in the interface so my app always knows the methods are going to be there.
我想知道的是,除了拥有一堆公共函数find($ id){return parent :: find($ id) )}
在做扩展雄辩模型的模型中输入方法有一种简单的方法让接口知道该方法是通过 __调用来处理的
?
What I want to know is, other than having a bunch of public function find($id){return parent::find($id)}
type methods in the models that do extend the eloquent model is there an easy way to let the interface know that the method is handled via __call
?
推荐答案
虽然对于这种设计的清洁度可能存在更大的问题,但是通过使用实现接口方法的特征可以完成类似于此的事情:
Although there may be a larger question as to the cleanliness of such a design, you can accomplish something akin to this by using a trait which implements the methods of the interface:
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's burn him anyway.";
}
}
print (new User)->find(123);
print (new NonmagicalUser)->find(321);
这篇关于通过__call实现通知接口方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!