我们可以在 php 中的另一个类中创建一个类的对象吗?我在 php 中做了一个小应用程序,现在我试图以类-方法-对象的方式转换整个代码。我现在很困惑。
最佳答案
你可以这样做,但是你是否应该这样做取决于两个类的生命周期和它们之间的关系。基本上,您可以在 Composition 之间进行选择。和 Aggregation .
组成
当创建的对象的生命周期等于或小于将使用它的对象时,您使用组合,例如
class A
{
private $belongsToAOnly;
public function __construct()
{
$this->belongsToAOnly = new IBelongToA;
}
}
在这种情况下,A
“拥有”IBelongToA
。当A
被销毁时,IBelongToA
也被销毁。它不能独立存在,很可能只是 A
的一个实现细节。它可能是 ValueObject喜欢Money
或其他一些数据类型。
摘自 Craig Larman 的“应用 UML 和模式”:
the composite is responsible for creation and deletion of it's parts - either by itself creating/deleting the parts, or by collaborating with other objects. Related to this constraint is that if the composite is destroyed, its parts must be destroyed, or attached to another composite"
聚合
当创建的对象的生命周期较长时使用聚合:
class A
{
private $dbAdapter;
public function __construct(DbAdapter $dbAdapter)
{
$this->dbAdapter = $dbAdapter;
}
}
与组合不同,这里没有所有权的暗示。 A
使用 DbAdapter
但当 A
被销毁时 DBAdapter
继续存在。这是一种“使用”关系,而不是“拥有”关系。
创造者模式(GRASP)
在 Creator Pattern in GRASP 中可以找到一个很好的启发式方法来决定一个对象何时可以在运行时创建另一个对象。它指出对象可以在以下情况下创建其他对象
- Instances of B contains or compositely aggregates instances of A
- Instances of B record instances of A
- Instances of B closely use instances of A
- Instances of B have the initializing information for instances of A and pass it on creation.
或者,您可以在需要创建某物的实例并聚合工厂实例时创建工厂,这将为您提供更清晰的separation of collaborators and creators .
可测试性
在对象中创建对象的一个问题是它们很难测试。当您进行单元测试时,您通常不想重新创建和引导整个系统环境,而是专注于单独测试那个特定的类。为此,您使用 Mock Objects 交换该类的依赖项。 .当您使用 Composition 时,您不能这样做。
因此,根据类的协作者所做的事情,您可能希望决定始终使用聚合,因为这样您就可以有效地做 Dependency Injection一路走来,这将使您可以轻松地更换一个类(class)的合作者,例如用 Mocks 代替他们。
关于php - 我们可以在 php 中的另一个类中创建一个类的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10634014/