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

Transactional Bundle Laravel Package

dmp/transactional-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require dmp/transactional-bundle
    

    Register the bundle in config/app.php under providers:

    Dmp\TransactionalBundle\TransactionalBundle::class,
    
  2. First Use Case Annotate a method with @Transactional to wrap it in a Doctrine transaction:

    use Dmp\TransactionalBundle\Annotation\Transactional;
    
    class OrderService {
        /**
         * @Transactional
         */
        public function createOrder(Order $order) {
            $order->setStatus('pending');
            $orderRepository->save($order);
            // Transaction auto-commits on success
        }
    }
    
  3. Where to Look First

    • Check src/Annotation/Transactional.php for annotation details.
    • Review src/DependencyInjection/TransactionalExtension.php for configuration options.
    • Inspect src/Aspect/TransactionalAspect.php to understand the AOP logic.

Implementation Patterns

Core Workflows

  1. Basic Transactional Method

    /**
     * @Transactional
     */
    public function updateUser(User $user) {
        $user->setEmail('new@example.com');
        $this->userRepository->save($user);
        // Transaction handled automatically
    }
    
  2. Transactional Service Layer Group multiple repository calls under a single transaction:

    /**
     * @Transactional
     */
    public function processPayment(Payment $payment) {
        $payment->charge();
        $this->paymentRepository->save($payment);
        $this->notificationService->sendConfirmation($payment->getUser());
    }
    
  3. Conditional Transactions Use readOnly = true for read-only operations:

    /**
     * @Transactional(readOnly = true)
     */
    public function getUserOrders(User $user) {
        return $this->orderRepository->findBy(['user' => $user]);
    }
    
  4. Integration with Commands Apply to Artisan commands for CLI workflows:

    use Illuminate\Console\Command;
    use Dmp\TransactionalBundle\Annotation\Transactional;
    
    class ImportUsersCommand extends Command {
        /**
         * @Transactional
         */
        public function handle() {
            // Import logic here
        }
    }
    

Advanced Patterns

  • Custom Transaction Attributes Extend the annotation for custom behavior:

    /**
     * @Transactional(isolation = "SERIALIZABLE")
     */
    public function criticalOperation() { ... }
    
  • Nested Transactions Use propagation = "REQUIRES_NEW" for independent transactions:

    /**
     * @Transactional(propagation = "REQUIRES_NEW")
     */
    public function logActivity() { ... }
    
  • Event Listeners Apply to event handlers for transactional side effects:

    /**
     * @Transactional
     */
    public function handle(OrderPlaced $event) {
        $this->orderRepository->markAsProcessed($event->order);
    }
    

Gotchas and Tips

Common Pitfalls

  1. Annotation Parsing Issues

    • Ensure autoload-dev includes annotation paths in composer.json:
      "autoload-dev": {
          "psr-4": {
              "Dmp\\TransactionalBundle\\": "vendor/dmp/transactional-bundle/src"
          }
      }
      
    • Run composer dump-autoload after installation.
  2. Doctrine EntityManager Scope

    • The bundle assumes the default Doctrine EntityManager. For multiple EMs, configure explicitly:
      # config/transactional.yaml
      dmp_transactional:
          entity_manager: 'doctrine.orm.entity_manager_secondary'
      
  3. Exception Handling

    • Uncaught exceptions in @Transactional methods will roll back the transaction. Use try-catch for granular control:
      try {
          $this->transactionalService->createOrder($order);
      } catch (ValidationException $e) {
          // Handle validation errors without rolling back
      }
      
  4. Performance Overhead

    • Avoid annotating high-frequency, low-value methods (e.g., simple getters). Use readOnly = true for read operations.
  5. Circular Dependencies

    • Transactions cannot nest across service boundaries if services hold the same EM instance. Use REQUIRES_NEW for independent transactions.

Debugging Tips

  • Enable Logging Add to config/transactional.yaml:

    dmp_transactional:
        debug: true
    

    Logs will appear in storage/logs/laravel.log.

  • Check Aspect Weaving Verify the aspect is loaded by inspecting the container:

    $this->app->has('dmp.transactional.aspect');
    
  • Test Transactions Use DB::beginTransaction()/commit() in tests to verify rollback behavior:

    public function testTransactionalRollback() {
        DB::beginTransaction();
        $this->expectException(ValidationException::class);
        $this->service->createOrder($invalidOrder);
        DB::rollBack(); // Should roll back
    }
    

Extension Points

  1. Custom Transaction Managers Implement Dmp\TransactionalBundle\TransactionManagerInterface for non-Doctrine transactions (e.g., DBAL):

    class CustomTransactionManager implements TransactionManagerInterface {
        public function beginTransaction() { ... }
        public function commit() { ... }
        public function rollback() { ... }
    }
    

    Register in config/transactional.yaml:

    dmp_transactional:
        transaction_manager: 'App\Services\CustomTransactionManager'
    
  2. Aspect Configuration Override the aspect class in the bundle’s extension:

    // In a custom bundle
    public function load(array $configs) {
        $container->set('dmp.transactional.aspect', CustomTransactionalAspect::class);
    }
    
  3. Annotation Validation Extend Dmp\TransactionalBundle\Validator\TransactionalValidator to add custom rules (e.g., method-level restrictions).

  4. Post-Commit Hooks Use Doctrine lifecycle events for side effects after commit:

    $entityManager->getEventManager()->addEventListener(
        \Doctrine\ORM\Events::postCommit,
        function () { /* Post-commit logic */ }
    );
    
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