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

Platform Entity Bundle Laravel Package

digitalstate/platform-entity-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require digitalstate/platform-entity-bundle
    

    Ensure DigitalState\PlatformEntityBundle\DigitalStatePlatformEntityBundle::class is registered in config/bundles.php.

  2. First Use Case: Extend an existing entity (e.g., App\Entity\Product) with platform-specific attributes:

    use DigitalState\PlatformEntityBundle\Entity\PlatformEntityInterface;
    
    class Product implements PlatformEntityInterface
    {
        use PlatformEntityTrait;
    
        // Your existing fields...
    }
    

    Run migrations (php bin/console doctrine:migrations:diff + php bin/console doctrine:migrations:migrate).

  3. Key Files to Review:

    • src/Entity/PlatformEntityTrait.php (core trait for entity behavior).
    • src/DependencyInjection/ (configuration and services).
    • src/Repository/ (custom repository methods).

Implementation Patterns

Core Workflows

1. Entity Extension

  • Pattern: Use PlatformEntityTrait to add platform-specific fields (e.g., createdAt, updatedAt, deletedAt soft-delete, or custom metadata).
  • Example:
    class Article implements PlatformEntityInterface
    {
        use PlatformEntityTrait;
    
        #[ORM\Column(type: 'string', length: 255)]
        private ?string $slug = null;
    
        // Automatically gets platform fields (e.g., `createdAt`, `isActive`).
    }
    

2. Data Resolvers

  • Pattern: Resolve entity data dynamically (e.g., for APIs or forms) using DataResolver services.
  • Example:
    // In a controller or service:
    $resolver = $this->container->get('digitalstate_platform_entity.data_resolver.article');
    $data = $resolver->resolve($articleEntity);
    

3. Form Handlers

  • Pattern: Handle form submissions with pre/post-processing via FormHandler interfaces.
  • Example:
    // Define a custom handler:
    class ArticleFormHandler implements FormHandlerInterface
    {
        public function handle(Article $entity, array $data): void
        {
            $entity->setSlug(Str::slug($data['title']));
        }
    }
    
    // Register in services.yaml:
    services:
        App\Form\Handler\ArticleFormHandler:
            tags: ['digitalstate.platform_entity.form_handler']
    

4. Repositories

  • Pattern: Extend base repositories with platform-specific queries.
  • Example:
    class ArticleRepository extends ServiceEntityRepository
    {
        public function findActiveWithSlug(string $slug): ?Article
        {
            return $this->createQueryBuilder('a')
                ->andWhere('a.slug = :slug')
                ->andWhere('a.isActive = :active')
                ->setParameter('slug', $slug)
                ->setParameter('active', true)
                ->getQuery()
                ->getOneOrNullResult();
        }
    }
    

5. Controllers

  • Pattern: Use platform-aware controllers for CRUD operations.
  • Example:
    class ArticleController extends AbstractPlatformController
    {
        public function index(DataResolverInterface $resolver): Response
        {
            $articles = $resolver->resolveCollection(Article::class);
            return $this->json($articles);
        }
    }
    

Integration Tips

  • Doctrine Events: Listen for prePersist, preUpdate, etc., to auto-set platform fields (e.g., createdAt).
    $entityManager->getEventManager()->addEventSubscriber(new PlatformEntitySubscriber());
    
  • Symfony Forms: Integrate with FormHandler for seamless validation and processing.
    $form = $this->createForm(ArticleType::class, $article);
    $form->handleRequest($request);
    $this->formHandler->handle($article, $form->getData());
    
  • API Platform: Use DataResolver to customize serialization/deserialization.
    # config/api_platform/resources.yaml
    resources:
        App\Entity\Article:
            collectionOperations:
                get:
                    method: 'GET'
                    path: '/articles'
                    controller: 'digitalstate_platform_entity.controller.article'
    

Gotchas and Tips

Pitfalls

  1. Trait Overload:

    • Avoid overriding PlatformEntityTrait methods unless necessary. Prefer composition (e.g., add custom methods to the entity class).
    • Fix: Extend the trait’s behavior via events or services.
  2. Migration Conflicts:

    • Adding PlatformEntityTrait to an existing entity may require manual migration adjustments (e.g., createdAt/updatedAt columns).
    • Fix: Run php bin/console doctrine:schema:update --dump-sql to preview changes.
  3. Circular Dependencies:

    • The bundle assumes OroEntityBundle is installed. If missing, install it first:
      composer require oro/platform
      
  4. Data Resolver Caching:

    • Resolvers may cache data aggressively. Clear cache after entity changes:
      php bin/console cache:clear
      

Debugging

  • Enable SQL Logging:
    # config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  • Check Events: Use Symfony’s event dispatcher to debug lifecycle callbacks:
    $dispatcher->addListener(PlatformEntityEvents::PRE_PERSIST, function ($event) {
        error_log('Pre-persist triggered for: ' . get_class($event->getEntity()));
    });
    

Configuration Quirks

  1. Custom Field Mapping:
    • Override default field mappings in config/packages/digitalstate_platform_entity.yaml:
      digitalstate_platform_entity:
          fields:
              created_at: 'creationDate'  # Custom column name
      
  2. Soft Delete:
    • Enable soft-delete globally:
      digitalstate_platform_entity:
          soft_delete: true
      
    • Manually restore entities:
      $entityManager->getRepository(Article::class)->restore($article);
      

Extension Points

  1. Custom Attributes:
    • Add platform-specific attributes via Doctrine extensions:
      use DigitalState\PlatformEntityBundle\Attribute\PlatformAttribute;
      
      #[PlatformAttribute]
      class CustomAttribute extends Attribute
      {
          public function load(PlatformEntityInterface $entity, array $data): void
          {
              $entity->setCustomField($data['value']);
          }
      }
      
  2. Event Subscribers:
    • Subscribe to platform events (e.g., PlatformEntityEvents::POST_UPDATE):
      class CustomSubscriber implements EventSubscriberInterface
      {
          public static function getSubscribedEvents(): array
          {
              return [
                  PlatformEntityEvents::POST_UPDATE => 'onPostUpdate',
              ];
          }
      
          public function onPostUpdate(PlatformEntityEvent $event): void
          {
              // Custom logic after update.
          }
      }
      
  3. Repository Decorators:
    • Decorate base repositories to add platform logic:
      class PlatformArticleRepository extends ArticleRepository
      {
          public function __construct(PlatformEntityManager $em)
          {
              parent::__construct($em);
          }
      
          public function findWithPlatformData(): array
          {
              // Custom query with platform fields.
          }
      }
      
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver