Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Base Entities Bundle Laravel Package

blast-project/base-entities-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require blast-project/base-entities-bundle
    

    Ensure LibrinfoDoctrineBundle and SonataAdminBundle are installed (this bundle extends their integration).

  2. Bundle Registration Add to config/bundles.php:

    return [
        // ...
        Blast\BaseEntitiesBundle\BlastBaseEntitiesBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Base Entity Traits Extend your Doctrine entity with the provided traits (e.g., Blast\BaseEntitiesBundle\Entity\Traits\Timestampable):

    use Blast\BaseEntitiesBundle\Entity\Traits\Timestampable;
    
    #[ORM\Entity]
    class User
    {
        use Timestampable;
        // ...
    }
    
  4. Sonata Admin Integration Extend your admin class with Blast\BaseEntitiesBundle\Admin\BaseAdmin:

    use Blast\BaseEntitiesBundle\Admin\BaseAdmin;
    
    class UserAdmin extends BaseAdmin
    {
        protected function configureFields(FieldMapInterface $fieldMap): void
        {
            $fieldMap->add('createdAt', null, [
                'editable' => false,
                'label' => 'Created At',
            ]);
        }
    }
    

Implementation Patterns

Common Workflows

  1. Timestampable Entities Automatically add createdAt and updatedAt fields via Timestampable trait:

    use Blast\BaseEntitiesBundle\Entity\Traits\Timestampable;
    
    #[ORM\Entity]
    class Post
    {
        use Timestampable;
        // ...
    }
    
  2. Soft Deletes Use SoftDeletable trait for soft-delete functionality:

    use Blast\BaseEntitiesBundle\Entity\Traits\SoftDeletable;
    
    #[ORM\Entity]
    class Comment
    {
        use SoftDeletable;
        // ...
    }
    

    Query with:

    $repository->findAllNonDeleted();
    
  3. Sonata Admin Enhancements Override configureListFields() or configureDatagridFields() in your admin class to leverage base behaviors:

    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        $datagridMapper->add('deletedAt', null, [
            'field_type' => Filter\Type\DateFilter::class,
            'label' => 'Deleted At',
        ]);
    }
    
  4. Custom Base Admin Logic Extend BaseAdmin to reuse common CRUD logic:

    class ProductAdmin extends BaseAdmin
    {
        protected function configureFormFields(FormMapper $formMapper): void
        {
            $this->addFormField($formMapper, 'name');
            $this->addFormField($formMapper, 'price', 'money');
        }
    }
    

Integration Tips

  • Doctrine Lifecycle Callbacks: The bundle hooks into prePersist, preUpdate, and preRemove for timestamp/soft-delete logic. Avoid overriding these methods unless necessary.
  • Sonata Admin Overrides: Prefer extending BaseAdmin over rewriting core Sonata logic. Use configure*() methods for customization.
  • QueryBuilder Extensions: The bundle adds methods like addNonDeletedFilter() to SonataAdmin's DatagridMapper. Use these in configureDatagridFilters():
    $datagridMapper->add('isActive', null, [
        'field_type' => Filter\Type\BooleanFilter::class,
    ]);
    $this->addNonDeletedFilter($datagridMapper);
    

Gotchas and Tips

Pitfalls

  1. Trait Conflicts

    • Avoid mixing traits from this bundle with other timestamp/soft-delete traits (e.g., Gedmo). Conflicts may arise in Doctrine lifecycle callbacks.
    • Fix: Use preUpdate/prePersist guards to check for trait presence:
      if (!method_exists($this, 'setUpdatedAt')) {
          $this->setUpdatedAt(new \DateTime());
      }
      
  2. Sonata Admin Caching

    • Changes to BaseAdmin or field configurations may not reflect immediately due to Sonata’s cache. Clear cache after updates:
      php bin/console cache:clear
      
  3. Soft Delete Queries

    • Forgetting to use findAllNonDeleted() or createQueryBuilderNonDeleted() will include deleted records.
    • Tip: Create a base repository method:
      public function findAllActive(): array
      {
          return $this->findAllNonDeleted(['deletedAt' => null]);
      }
      
  4. Timestamp Precision

    • The bundle uses DateTime by default. For microsecond precision, override the trait’s getUpdatedAt():
      public function getUpdatedAt(): ?\DateTimeInterface
      {
          return $this->updatedAt?->setTimezone(new \DateTimeZone('UTC'));
      }
      

Debugging

  • Lifecycle Events: Enable Doctrine debug mode to trace callback issues:
    # config/packages/dev/doctrine.yaml
    doctrine:
        orm:
            entity_managers:
                default:
                    logging: true
                    dbal:
                        logging: true
    
  • Sonata Admin Logs: Check var/log/dev.log for admin-related errors, especially after extending BaseAdmin.

Extension Points

  1. Custom Traits Extend existing traits (e.g., Timestampable) by creating your own:

    namespace App\Entity\Traits;
    
    use Blast\BaseEntitiesBundle\Entity\Traits\Timestampable;
    
    trait AuditTimestampable
    {
        use Timestampable;
    
        #[ORM\Column]
        private ?\DateTimeInterface $auditedAt = null;
    
        public function setAuditedAt(?\DateTimeInterface $auditedAt): self
        {
            $this->auditedAt = $auditedAt;
            return $this;
        }
    }
    
  2. Admin Overrides Override BaseAdmin methods like configureListFields() to add custom logic:

    protected function configureListFields(ListMapper $listMapper): void
    {
        $listMapper
            ->add('id')
            ->add('name')
            ->add('_action', 'actions', [
                'actions' => [
                    'edit' => [],
                    'delete' => ['template' => 'BlastBaseEntitiesBundle:CRUD:delete_soft.html.twig'],
                ],
            ]);
    }
    
  3. QueryBuilder Helpers Add custom methods to BaseAdmin for reusable queries:

    protected function addActiveFilter(DatagridMapper $datagridMapper): void
    {
        $datagridMapper->add('isActive', null, [
            'field_type' => Filter\Type\BooleanFilter::class,
            'label' => 'Active',
        ]);
    }
    

Configuration Quirks

  • Database Defaults: Ensure your database supports DATETIME/TIMESTAMP for timestamp fields. MySQL/MariaDB require explicit column types:
    #[ORM\Column(type: 'datetime', nullable: true)]
    private ?\DateTimeInterface $deletedAt = null;
    
  • Timezones: The bundle defaults to UTC. Override getCreatedAt()/getUpdatedAt() to handle timezones:
    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt?->setTimezone(new \DateTimeZone('Europe/Paris'));
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware