如何在 Symfony 4.x 中为 'reusable bundle' 配置 'entities'?

How to configure 'entities' for a 'reusable bundle' in Symfony 4.x?

我在使用 symfony 4.x,我为 easyadmin 附加组件创建了一个可重用的包。我创建了一个众所周知的实体,但在提交数据时,我有一个未检测到的 HasLifecycleCallbacks 方法 _prePersist。

/**
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Table
 * @ORM\Entity
 */
class Post
{}
/**
 * @ORM\PrePersist
 */
public function _prePersist()
{
  dump($this);die;
}

您将需要更新 Bundle 的配置以注册您保存实体的文件夹以及可能的生命周期事件。将它们放在 src/Entity 中时,这是没有必要的,因为 DoctrineBundle 已经为此提供了默认配置。这就是为什么在您的 config/packages/doctrine.yaml 中有以下内容:

doctrine:
    orm:
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

您应该跟踪 DoctrineBundle 如何从 Configuration.php and then how the Service Container is configured from these config values by looking at DoctrineExtension.php 读取和处理此配置。您可能可以省略配置文件,但是您的 MyBundleExtension 需要使用包内的实体 类 更新 Doctrine-services。

或者,您可以查看食谱,而不是将实体保留在您的捆绑包中,只要安装了您的捆绑包,就将其复制到 src/ 目录中。由于食谱的工作原理,您的捆绑包需要为此开源,并且您必须提供 contrib-recipe for this bundle.

编辑:另一种选择是为您的基本设置提供完整的框架,这样您就不必担心捆绑包和独立配置,而只需提供一个带有您认为有用的默认设置的基本入门应用程序.