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

Dynamic Orm Value Bundle Laravel Package

dualmedia/dynamic-orm-value-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require dualmedia/dynamic-orm-value-bundle
    

    Register the bundle in config/bundles.php:

    DualMedia\DynamicORMValueBundle\DynamicORMValueBundle::class => ['all' => true],
    
  2. Configure Entity Paths Create config/packages/dm_dynamic_orm.yaml:

    dm_dynamic_orm:
      entity_paths:
        - '%kernel.project_dir%/src/Entity'
    
  3. Annotate Your Entity Use the #[DynamicValue] attribute on a property to mark it for dynamic generation:

    use DualMedia\DynamicORMValueBundle\Attribute\DynamicValue;
    
    #[ORM\Entity]
    class Order
    {
        #[DynamicValue]
        private string $userFriendlyId;
    }
    
  4. First Use Case Persist an entity to auto-generate the dynamic value:

    $order = new Order();
    $entityManager->persist($order);
    $entityManager->flush(); // $order->userFriendlyId is now populated
    

Implementation Patterns

Core Workflow

  1. Marking Dynamic Fields Use #[DynamicValue] on properties that should be auto-generated during persist()/flush():

    #[DynamicValue(strategy: 'uuid')] // Optional: specify generation strategy
    private string $trackingCode;
    
  2. Custom Strategies Extend the default strategies (e.g., uuid, incremental) by implementing DynamicValueStrategyInterface:

    class CustomStrategy implements DynamicValueStrategyInterface
    {
        public function generate(): string
        {
            return 'CUSTOM-' . time();
        }
    }
    

    Register it in dm_dynamic_orm.yaml:

    dm_dynamic_orm:
      strategies:
        custom: DualMedia\DynamicORMValueBundle\Strategy\CustomStrategy
    

    Use it in your entity:

    #[DynamicValue(strategy: 'custom')]
    private string $customField;
    
  3. Conditional Generation Use the #[DynamicValue] if option to control when a value is generated:

    #[DynamicValue(if: 'this->isActive()')]
    private string $activeToken;
    
  4. Integration with Events Listen to prePersist/preUpdate to inject dynamic values manually:

    $entityManager->getEventManager()->addEventListener(
        ORMEvents::prePersist,
        function (PrePersistEventArgs $args) {
            $entity = $args->getObject();
            if ($entity instanceof Order && $entity->isReadyForFriendlyId()) {
                $entity->setUserFriendlyId('MANUAL-' . uniqid());
            }
        }
    );
    
  5. Bulk Operations For batch inserts, leverage EntityManager::flush() after setting dynamic values in a loop:

    foreach ($orders as $order) {
        $order->setUserFriendlyId('BATCH-' . $order->getId());
    }
    $entityManager->flush();
    

Gotchas and Tips

Pitfalls

  1. Circular Dependencies Avoid annotating properties that rely on other dynamic values in the same entity. The bundle processes fields in declaration order, which may lead to incomplete data if A depends on B and both are dynamic.

  2. Configuration Overrides If entity_paths is misconfigured, the bundle silently ignores annotated entities. Verify paths in dm_dynamic_orm.yaml and check for #[DynamicValue] attributes not triggering.

  3. Strategy Conflicts Custom strategies must implement DynamicValueStrategyInterface exactly. Missing methods (e.g., generate()) will throw BadMethodCallException at runtime.

  4. Doctrine Lifecycle Events Dynamic values generated in prePersist may not reflect in postPersist if the entity is modified afterward. Use postPersist for final adjustments:

    $entityManager->getEventManager()->addEventListener(
        ORMEvents::postPersist,
        function (PostPersistEventArgs $args) {
            $entity = $args->getObject();
            if ($entity instanceof Order) {
                $entity->setGeneratedAt(new \DateTime());
            }
        }
    );
    
  5. Performance with Large Batches Generating dynamic values for thousands of entities in a single flush() can cause delays. Consider:

    • Using a lighter strategy (e.g., incremental instead of uuid).
    • Processing in chunks with separate transactions.

Debugging Tips

  1. Enable Logging Add this to config/packages/monolog.yaml to log dynamic value generation:

    handlers:
        dynamic_orm:
            type: stream
            path: "%kernel.logs_dir%/dynamic_orm.log"
            level: debug
            channels: ["dynamic_orm"]
    

    Then configure the bundle to use the channel:

    dm_dynamic_orm:
        logging_channel: dynamic_orm
    
  2. Check Event Subscribers Ensure no other subscribers are overriding dynamic values. Inspect EventManager listeners:

    $listeners = $entityManager->getEventManager()->getListeners();
    print_r($listeners[ORMEvents::prePersist]);
    
  3. Validate Strategies Test strategies in isolation:

    $strategy = new \DualMedia\DynamicORMValueBundle\Strategy\UuidStrategy();
    var_dump($strategy->generate()); // Should output a UUID
    

Extension Points

  1. Custom Value Sources Implement DynamicValueSourceInterface to fetch values from external systems (e.g., APIs):

    class ApiValueSource implements DynamicValueSourceInterface
    {
        public function getValue(): string
        {
            return file_get_contents('https://api.example.com/value');
        }
    }
    

    Use it in dm_dynamic_orm.yaml:

    dm_dynamic_orm:
      sources:
        api: DualMedia\DynamicORMValueBundle\Source\ApiValueSource
    

    Annotate the entity:

    #[DynamicValue(source: 'api')]
    private string $externalValue;
    
  2. Post-Generation Hooks Extend the bundle’s DynamicValueGenerator to add logic after value generation:

    $generator = $container->get('dm_dynamic_orm.generator');
    $generator->addPostGenerateListener(
        Order::class,
        function (Order $order) {
            $order->setGeneratedAt(new \DateTime());
        }
    );
    
  3. Override Default Strategies Replace default strategies (e.g., uuid) by binding your implementation as a service:

    services:
        DualMedia\DynamicORMValueBundle\Strategy\UuidStrategy:
            class: App\Strategy\CustomUuidStrategy
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky