Class A
{
public function __construct(Foo $foo, Bar $bar, MyCustomType1 $mct)
{
//...
}
//...
public function getFooBarFunction()
{
$this->foo->aMethod();
$this->bar->anotherMethod();
//some other execution here
}
}
Class B
{
public function __construct(Foo $foo, Bar $bar, MyCustomType2 $mct)
{
//...
}
//...
public function getFooBarFunction()
{
$this->foo->aMethod();
$this->bar->anotherMethod();
//some other execution here (same of Class A)
}
}
Class C
{
public function __construct(Foo $foo, Bar $bar, MyCustomType3 $mct)
{
//...
}
//...
public function getFooBarFunction()
{
$this->foo->aMethod();
$this->bar->anotherMethod();
//some other execution here (same of Class B and Class A)
}
}
如您所见,这段代码并不符合DRY原则。我可以将
getFooBarFunction()
轻松地合并到另一个类中并使用该方法。A)创建一个超类并将
getFooBarFunction()
迁移到其中。我还需要复制__construct()
($this->
引用)。优点
- 很容易做到
- 我可以为
MyCustomType
(s)创建接口,并在构造函数中使用它们来代替具体的类缺点
- 如果子类需要在构造阶段添加参数怎么办?
- 如果我无法将
MyCustomType
(s)分组在同一接口下怎么办?B)创建一个超类并使用setter“注入”
Foo
和Bar
对象优点
- 也很容易
- 我不需要共享构造函数
缺点
- 如果我忘记注入参数怎么办?我必须向超类添加额外的显式检查并引发异常吗?
C)创建一个超类并让
getFooBarFunction()
接受Foo
和Bar
对象优点
- 也很容易
- 我不需要共享构造函数
缺点
- 在这种情况下,继承真的有必要吗?
D)创建一个独立的类(服务?),让
A
,B
,C
实例化它并直接使用它哪种方法最好(或“最佳实践”)以及为什么?还有其他方法吗?
更新
类A、类B和类C是一些彼此不共享任何信息的对象(它们表示一个Room
,一个Service
,一个Supplement
)。唯一共同的特点是每个类都与i18n表格相关联(每个类都有自己的表格)。因此,我的getFooBarFunction()
只是一个用于检索静态类型的函数(存储在某个地方,它不重要),该类型指示i18n文本的类型(标题、描述、简称等等)。
真实代码更新
private function getTextTypeNameEntity()
{
$text_type_repository = $this->getTextTypeRepository();
$text_type_name_id = $this->container->getParameter('foo_project.text_type.name');
$text_type_name = $text_type_repository->findOneById($text_type_name_id);
return $text_type_name;
}
这个函数是 getFooBarFunction()
2)
。 - georg