【问题标题】:Bundle to add attribute to another entity捆绑以将属性添加到另一个实体
【发布时间】:2018-05-20 14:13:45
【问题描述】:

你好,

我有一个实体 A:

  • 身份证
  • att1
  • att2

现在,我想添加一个新的 Bundle(它将添加新功能),特别是在这里我想为 A 添加一个属性。A 必须是这样的:

  • 身份证
  • att1
  • att2
  • 新的Att3
  • 新Att4

为了做到这一点,我正在考虑创建一个新实体,它将扩展 A 并添加新属性。

但是,我不知道的是,如果安装了第二个捆绑包,我该如何准备第一个捆绑包以使用第二个实体(和控制器/视图)?

我想我需要在第一个包中添加配置,但我不知道要添加什么...

谢谢!

【问题讨论】:

    标签: symfony configuration bundle symfony-2.7


    【解决方案1】:

    请阅读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。

    【讨论】:

      猜你喜欢
      • 2013-11-24
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多