PHP code example of randomstate / laravel-doctrine-entity-events

1. Go to this page and download the library: Download randomstate/laravel-doctrine-entity-events library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

randomstate / laravel-doctrine-entity-events example snippets




use RandomState\LaravelDoctrineEntityEvents\EventRedirector;

public class AppServiceProvider extends ServiceProvider {

    public function register() {
        EventRedirector::register(function(EventRedirector $redirector) {
           $redirector->redirect(MyEntity::class)
            ->postPersist(MyEntityWasCreated::class)
            ->postUpdate(MyEntityWasUpdated::class)
            ->postFlush() // falls back to default as no destination is provided
            ->default(SomethingHappenedToMyEntityEvent::class); 
        });
    }
}



use RandomState\LaravelDoctrineEntityEvents\EventRedirector;

public class AppServiceProvider extends ServiceProvider {

    public function register() {
        $this->app->resolving(EventRedirector::class, (function(EventRedirector $redirector) {
           $redirector->redirect(MyEntity::class)
            ->postPersist(MyEntityWasCreated::class)
            ->postUpdate(MyEntityWasUpdated::class)
            ->postFlush() // falls back to default as no destination is provided
            ->default(SomethingHappenedToMyEntityEvent::class); 
        }));
    }
}



class MyEntityWasCreated {
    
    public function __construct(MyEntity $entity, LifecycleEventArgs $eventArgs) {
        // do something
    }
    
    public function handle() {
        // do something
    }
    
}



EventRedirector::register(function(EventRedirector $redirector) {
           $redirector->redirect(MyEntity::class)
            ->postPersist(MyEntityWasCreated::class)
            ->postUpdate(function(MyEntity $entity) {
                $mailer = app('mailer');
                event(new MyEntityWasUpdated($entity, $mailer)); // customised instantiation
            })
            ->postFlush() // falls back to default as no destination is provided
            ->default(SomethingHappenedToMyEntityEvent::class); 
        });