请阅读Best Practices for Reusable Bundles
和Doctrine Inheritance Mapping
您也可以考虑Traits,但通常最好的方法是使用接口。在接口的帮助下,您可以像这样以一种干净的方式使您的包具有高度可配置性:
创建一个配置变量,告诉包应该使用什么类。这可以是 Bundle 中的默认 A 类,但也可以是 AppBundle 中的 A 类。
$rootNode
->children()
->scalarNode('a_entity')
->defaultValue('AppBundle\\Entity\\A')
->end()
->end()
;
然后为 A 类创建一个接口,其中包含所有必需的功能:
interface AInterface
{
public function setVariable($name, $var);
public function getHtml($template);
}
并在类中实现接口:
class A implements AInterface
{
// ...
}
每次如果您将类作为参数传递,请使用 AInterface 而不是 A:
class B
{
private $a;
public function __construct(AInterface $a)
{
$this->a = $a;
}
}
现在您可以将配置变量 a_entity 更改为另一个类。这个其他类仍然需要实现接口 AInterface。