StofDoctrineExtensionsBundle

repository·main·Indexed 24 days ago

https://github.com/stof/stofdoctrineextensionsbundle

A Symfony bundle that integrates the DoctrineExtensions library into Symfony projects. It enables advanced Doctrine features such as automatic timestamping, slug generation, translatable entities, and soft-deleteable filters for both ORM and MongoDB managers.

Tokens
4.4K
Snippets
9
Records
24
Agent score
84%

What's inside StofDoctrineExtensionsBundle

  1. Enable the SoftDeleteable Doctrine filter

    main

    To use the SoftDeleteable behavior, you must enable the corresponding Doctrine filter in your configuration. This ensures that entities marked as deleted are automatically excluded from queries.

    If you are using Symfony Flex, add the configuration to config/packages/doctrine.yaml. If you are using the traditional app/config/config.yml, add it there instead.

    Note: If you use multiple entity managers, ensure you register the filter for the specific entity manager you are using.

    # app/config/config.yml
    # (or config/packages/doctrine.yaml if you use Flex)
    doctrine:
        orm:
            entity_managers:
                default:
                    filters:
                        softdeleteable:
                            class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
                            enabled: true
  2. Install StofDoctrineExtensionsBundle using Symfony Flex

    main

    If your Symfony project (version 3.4 or higher) uses Symfony Flex, you can install and automatically configure the bundle by running a single Composer command. Flex will handle downloading, registering, and configuring the bundle for you.

    $ composer require stof/doctrine-extensions-bundle
  3. Override bundle listeners with custom classes

    main

    You can replace the default Gedmo listeners (or the bundle's translation listeners) with your own custom implementations. To do this, provide the fully qualified class name of your custom listener in the stof_doctrine_extensions.class configuration section. If you want to keep the default listener for a specific extension, use the tilde (~) character.

    # config/packages/stof_doctrine_extensions.yaml
    stof_doctrine_extensions:
        class:
            tree:           MyBundle\TreeListener
            timestampable:  MyBundle\TimestampableListener
            blameable:      ~
            sluggable:      ~
            translatable:   ~
            loggable:       ~
            softdeleteable: ~
            uploadable:     ~
  4. Register extension mappings in Doctrine

    main

    Some extensions (like Translatable, Translator, Loggable, and Tree) use their own internal entities. You must register these mappings in your Doctrine configuration so Doctrine can recognize them. If you add these mappings, you must generate and execute a migration to create the necessary database tables.

    For ORM, use the mappings key under your entity manager. For MongoDB, the documents are located in the Document subnamespace instead of Entity.

    # app/config/config.yml
    # (or config/packages/doctrine.yaml)
    doctrine:
        orm:
            entity_managers:
                default:
                    mappings:
                        gedmo_translatable:
                            type: attribute
                            prefix: Gedmo\Translatable\Entity
                            dir: "%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Translatable/Entity"
                            alias: GedmoTranslatable
                        gedmo_translator:
                            type: attribute
                            prefix: Gedmo\Translator\Entity
                            dir: "%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Translator/Entity"
                            alias: GedmoTranslator
                        gedmo_loggable:
                            type: attribute
                            prefix: Gedmo\Loggable\Entity
                            dir: "%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Loggable/Entity"
                            alias: GedmoLoggable
                        gedmo_tree:
                            type: attribute
                            prefix: Gedmo\Tree\Entity
                            dir: "%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Tree/Entity"
                            alias: GedmoTree
  5. Install StofDoctrineExtensionsBundle without Symfony Flex

    main

    If your project does not use Symfony Flex, you must manually download and register the bundle following these two steps:

    Step 1: Download the Bundle

    Run the following command in your project directory to download the latest stable version:

    $ composer require stof/doctrine-extensions-bundle

    Step 2: Enable the Bundle

    Manually register the bundle in your app/AppKernel.php file by adding new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle() to the $bundles array within the registerBundles() method.

    // app/AppKernel.php
    
    class AppKernel extends Kernel
    {
        public function registerBundles()
        {
            $bundles = array(
                // ...
    
                new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
            );
    
            // ...
        }
    
        // ...
    }
  6. Activate specific extensions for an entity manager

    main

    By default, the bundle does not attach any listeners. You must declare which extensions you want to enable for each entity manager.

    Warning: If you configure listeners for an entity manager across multiple configuration files, only the last one loaded will be used. You must list all desired listeners in the final configuration file to ensure they are all active.

    # app/config/config.yml
    # (or config/packages/stof_doctrine_extensions.yaml)
    stof_doctrine_extensions:
        default_locale: en_US
        orm:
            default:
                tree: true
                timestampable: false
                translatable: false
                blameable: false
                sluggable: false
                loggable: false
                ip_traceable: false
                sortable: false
                softdeleteable: false
                uploadable: false
                reference_integrity: false
            other:
                timestampable: true
  7. Use the Uploadable extension to handle file uploads

    main

    To use the Uploadable extension with Symfony forms, follow these steps after verifying that your form is valid:

    1. Persist your entity using the Doctrine EntityManager.
    2. Retrieve the stof_doctrine_extensions.uploadable.manager service.
    3. Call markEntityToUpload($entity, $uploadedFile) on the uploadable manager. The second argument should be the UploadedFile instance that was bound to your entity property by the form.
    4. Flush the EntityManager.

    The extension will then handle the actual file movement and metadata management automatically.

    $document = new Document();
    $form = $this->createFormBuilder($document)
        ->add('name')
        ->add('myFile')
        ->getForm()
    ;
    
    $form->handleRequest($request);
    
    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($document);
    
        $uploadableManager = $this->get('stof_doctrine_extensions.uploadable.manager');
    
        // Here, "getMyFile" returns the "UploadedFile" instance that the form bound in your $myFile property
        $uploadableManager->markEntityToUpload($document, $document->getMyFile());
    
        $em->flush();
    
        return $this->redirect($this->generateUrl('...'));
    }
  8. Configure StofDoctrineExtensionsBundle entity managers

    main

    You must explicitly activate extensions for each entity manager (ORM) or document manager (MongoDB) you wish to use. The bundle requires a default_locale (defaults to en) to be used when a translation is missing for the requested language.

    In YAML, use the stof_doctrine_extensions key. In XML, use the stof-doctrine-extensions namespace.

    # app/config/config.yml
    # (or config/packages/stof_doctrine_extensions.yaml)
    stof_doctrine_extensions:
        default_locale: en_US
    
        # Only used if you activated the Uploadable extension
        uploadable:
            default_file_path:       "%kernel.project_dir%/public/uploads"
            mime_type_guesser_class: Stof\DoctrineExtensionsBundle\Uploadable\MimeTypeGuesserAdapter
            default_file_info_class: Stof\DoctrineExtensionsBundle\Uploadable\UploadedFileInfo
    
        orm:
            default: ~
        mongodb:
            default: ~
  9. Configure the Uploadable extension

    main

    If the uploadable extension is activated, you can customize its behavior using the following keys:

    • default_file_path: The path where files will be stored. One of three ways to configure the path.
    • mime_type_guesser_class: (Optional) The class used to guess MIME types. Defaults to a Symfony Mime component adapter.
    • default_file_info_class: (Optional) The class implementing FileInfoInterface used to handle file info. Defaults to Stof\DoctrineExtensionsBundle\Uploadable\UploadedFileInfo which is prepared for UploadedFile instances.
  10. Configure StofDoctrineExtensionsBundle settings

    main

    The bundle is configured under the stof_doctrine_extensions key in your Symfony configuration files (e.g., config/packages/stof_doctrine_extensions.yaml).

    Global settings include:

    • default_locale: The default locale used for translations (defaults to en).
    • translation_fallback: Whether to fallback to the default locale if a translation is missing.
    • persist_default_translation: Whether to persist the default translation.
    • skip_translation_on_load: Whether to skip translation loading on entity load.
    • metadata_cache_pool: The cache pool used for metadata.