PHP:具有共享方法的方法链
这是我一段时间以来一直在思考的事情。我想将一组方法链接在一起,如下所示的示例。
方法链接的概念很简单,但我想要的是让我们所有的动物都通过相同的 add
方法添加,那么我应该如何弄清楚我们要添加什么类型的动物在 add
方法中?
$zoo = new Zoo;
$lion = $zoo->lion->add('Lucas the lion');
$cockatoo = $zoo->cockatoo->add('Chris the cockatoo');
class Zoo {
function add($name) {
//How to figure out if the animal is a Lion or an Cockatoo?
}
}
Here's something that I've been thinking about for some time. I want to chain together a set of methods like in the below shown example.
The concept of method chaining is no brainer, but what I want is to make all of our animals be added through the same add
method, so how should I figure out what type of animal that we're adding inside the add
method?
$zoo = new Zoo;
$lion = $zoo->lion->add('Lucas the lion');
$cockatoo = $zoo->cockatoo->add('Chris the cockatoo');
class Zoo {
function add($name) {
//How to figure out if the animal is a Lion or an Cockatoo?
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于我们正在谈论面向对象设计,因此实现层次结构会更加“正确”和灵活,例如:
Since we're talking about Object Oriented Design it would be much more "correct" and flexible to implement hierarchy like:
该问题的一种解决方案是重写 Zoo 类中的 __get 以返回“创建者”类。
然后让creator类调用zoo类中的add函数。
这个解决方案相当丑陋,而且从未来开发人员的角度来看,也不太清楚。正如评论中指出的,有更好的方法可以做到这一点。做类似的事情:
或者
可能是一个更好的解决方案,在我看来,其他开发人员很清楚发生了什么。 (这对你来说可能不是这样,因为我不知道你到底在做什么的细节)。
One solution to the problem would be to override __get in the Zoo class to return a 'creator' class.
Then let the creator class call the add function in the zoo class.
This solution is fairly ugly, and from a future developers perspective, not that clear. As pointed out in the comments, there are better ways about going this. Doing something like:
or
May be a better solution and in my opinion it is far clear to other developers what is happening. (This may not be the case for you, as I don't know the details of exactly what you are doing).