Search code examples
phpsymfonysymfony4

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


I'm on symfony 4.x, I created a reusable bundle for an easyadmin add-on. I create an entity that is well known but when submitting data, I have a method _prePersist for HasLifecycleCallbacks that is not detected.

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

Solution

  • You will need to update your Bundle's configuration to register both the folder where you keep your entities and probably the lifecycle events as well. When placing them in src/Entity this is not necessary, because the DoctrineBundle already provides default configuration for that. This is why in your config/packages/doctrine.yaml you have the following:

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

    You should track how the DoctrineBundle reads & processes this configuration from the Configuration.php and then how the Service Container is configured from these config values by looking at DoctrineExtension.php. You can probably omit the Configuration file, but your MyBundleExtension needs to update the Doctrine-services with your entity classes from inside the bundle.

    Alternatively you can look at Recipes and instead of keeping the Entity in your bundle copy it into the src/ directory whenever your bundle is installed. Due to how recipes work, your bundle will need to be open source for this and you will have to provide a contrib-recipe for this bundle.

    edit: Another option could be to provide a full skeleton for your basic setup, so that you don't need to worry about bundles and independent configuration and instead just provide a basic starter application with a default setup you deem useful.