使用基类在多个类之间共享对象
这篇文章与我的需求类似,但我更好奇的是它的具体解决方案,以及这样做是好还是坏。 在 PHP 类之间共享对象
比如说,就像上面的链接一样,我有一个对象想要传递给多个类,比如 $db 对象。
让所有类扩展一个将 $db 对象存储为属性的 Base 类,而不是使用依赖注入并将其传递给每个方法的构造函数,这是否是一个好主意?
例如:
abstract class Base {
protected static $_db;
public function setDatabase( Database $db ) {
$this->_db = $db;
}
public function getDatabase() {
return $this->_db;
}
}
class SomeClass extends Base {
public function doStuff() {
$result = $this->getDatabase()->query(.....);
}
}
这意味着扩展 Base 的所有类都不必担心自己抓取/检查/设置 $db,因为一旦定义了该类,它们就已经将该对象作为属性了。
我知道依赖注入是通常的方法,但这是否是一个可行的解决方案?
谢谢!
This article is similar to my needs, but I'm more curious about a specific solution to it, and if it's a good or bad idea to do it. Sharing objects between PHP classes
Say, like in the link above, I have an object I want to pass to multiple classes, say a $db object.
Instead of using dependency injection and passing it to each method's constructor, is it ever a good idea to let all the classes extend a Base class, that stores the $db object as a property?
For example:
abstract class Base {
protected static $_db;
public function setDatabase( Database $db ) {
$this->_db = $db;
}
public function getDatabase() {
return $this->_db;
}
}
class SomeClass extends Base {
public function doStuff() {
$result = $this->getDatabase()->query(.....);
}
}
Which would mean all classes that extend Base need not worry about grabbing/checking/setting the $db themselves, as they'd already have that object as a property as soon as the class is defined.
I know dependency injection is the usual way to go, but is this ever a viable solution?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您仍然必须在类的每个实例上设置数据库 - 在一个实例上设置它并不会在所有实例上设置它......当然除非它是一个静态属性。
You still have to set the db on each instance of the class - setting it on one instance doesnt set it on all instances... unless of course its a
static
property.那完全没问题。我以前用过它,从未遇到过任何问题。
That is perfectly fine. I have used it before and never ran into any issues.