PHP code example of nilportugues / messagebus

1. Go to this page and download the library: Download nilportugues/messagebus 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/ */

    

nilportugues / messagebus example snippets



use NilPortugues\MessageBus\CommandBus\Contracts\Command;

final class RegisterUser implements Command
{
    private $username;
    private $password;
    private $emailAddress;
    
    public function __construct(string $username, string $password, string $emailAddress)
    {
        $this->username = $username;
        $this->password = $password;
        $this->emailAddress = $emailAddress;
    }
    
    //getters...
}


use NilPortugues\MessageBus\CommandBus\Contracts\CommandHandler;
use NilPortugues\MessageBus\CommandBus\Contracts\Command;

final class RegisterUserHandler implements CommandHandler
{
    private $userRepository;
    
    public function __construct($userRepository)
    {
        $this->userRepository = $userRepository;
    }
        
    public function __invoke(RegisterUser $command)
    {        
        $user = new User(
            $command->getUsername(),
            $command->getPassword(),
            $command->getEmail(),
        );
        
        $this->userRepository->save($user);        
    }    
}


//...your other registered classes

$container['RegisterUserHandler'] = function($container) {
    return new RegisterUserHandler($container->get('UserRepository');
};


//...your other registered classes

$container['CommandTranslator'] = function($container) {
    return new \NilPortugues\MessageBus\CommandBus\Translator\AppendStrategy('Handler');
};

$container['CommandHandlerResolver'] = function($container) {
    return new \NilPortugues\MessageBus\CommandBus\Resolver\PsrContainerResolver($container);
};

$container['CommandBusMiddleware'] = function($container) {
    return new \NilPortugues\MessageBus\CommandBus\CommandBusMiddleware(
        $container->get('CommandTranslator'),
        $container->get('CommandHandlerResolver'),
    );
};

$container['CommandBus'] = function($container) {
    return new \NilPortugues\MessageBus\CommandBus\CommandBus([  
        $container->get('CommandBusMiddleware'),
    ]);
};


//...your other registered classes

$container['LoggerCommandBusMiddleware'] = function($container) {
    return new \NilPortugues\MessageBus\CommandBus\LoggerCommandBusMiddleware(
        $container->get('Monolog')
    );
};

//Update the CommandBus with the LoggerCommandBusMiddleware
$container['CommandBus'] = function($container) {
    return new \NilPortugues\MessageBus\CommandBus\CommandBus([
        $container->get('LoggerCommandBusMiddleware'),
        $container->get('CommandBusMiddleware'),
    ]);
};


$commandBus = $container->get('CommandBus');
$command = new RegisterUser('MyUsername', 'MySecretPassword', '[email protected]');
$commandBus($command);


use NilPortugues\MessageBus\QueryBus\Contracts\Query;

final class GetUser implements Query
{
    private $userId;
    
    public function __construct(string $userId) 
    {
        $this->userId = $userId;    
    }
    
    public function getUserId() : string
    {
        return $this->userId;
    }
}


use NilPortugues\MessageBus\QueryBus\Contracts\Query;
use NilPortugues\MessageBus\QueryBus\Contracts\QueryHandler;
use NilPortugues\MessageBus\QueryBus\Contracts\QueryResponse;

final class GetUserHandler implements QueryHandler
{
    private $userRepository;
    
    public function __construct($userRepository)
    {
        $this->userRepository = $userRepository;
    }
        
    public function __invoke(GetUser $query) : QueryResponse
    {  
        $userId = $query->getUserId();        
        $user = $this->userRepository->find($userId);       
         
        return new UserQueryResponse($user);
    }
}



class UserQueryResponse implements QueryResponse
{
   public function __construct(User $user)
   {
        //fetch the relevant properties from the User object
   }
   
   //..getters. No setters 


//...your other registered classes

$container['GetUserHandler'] = function($container) {
    return new GetUserHandler($container->get('UserRepository'));
};


//...your other registered classes

$container['QueryTranslator'] = function($container) {
    return new \NilPortugues\MessageBus\QueryBus\Translator\AppendStrategy('Handler');
};

$container['QueryHandlerResolver'] = function($container) {
    return new \NilPortugues\MessageBus\QueryBus\Resolver\PsrContainerResolver($container);
};

$container['QueryBusMiddleware'] = function($container) {
    return new \NilPortugues\MessageBus\QueryBus\QueryBusMiddleware(
        $container->get('QueryTranslator'),
        $container->get('QueryHandlerResolver'),
    );
};

$container['QueryBus'] = function($container) {
    return new \NilPortugues\MessageBus\QueryBus\QueryBus([  
        $container->get('QueryBusMiddleware'),
    ]);
};


//...your other registered classes

$container['LoggerQueryBusMiddleware'] = function($container) {
    return new \NilPortugues\MessageBus\QueryBus\LoggerQueryBusMiddleware(
        $container->get('Monolog')
    );
};

//Update the QueryBus with the LoggerQueryBusMiddleware
$container['QueryBus'] = function($container) {
    return new \NilPortugues\MessageBus\QueryBus\QueryBus([
        $container->get('LoggerQueryBusMiddleware'),
        $container->get('QueryBusMiddleware'),
    ]);
};


$queryBus = $container->get('QueryBus');
$query = new GetUser(1):
$userQueryResponse = $queryBus($query);


use NilPortugues\MessageBus\EventBus\Contracts\Event;

final class UserRegistered implements Event
{
    private $userId;
    private $email;
    
    public function __construct(string $userId, string $email) 
    {
        $this->userId = $userId;    
        $this->email = $email;    
    }
    
    public function getUserId() : string
    {
        return $this->userId;
    }
    
    public function getEmail() : string
    {
        return $this->email;
    }
}


use NilPortugues\MessageBus\EventBus\Contracts\Event;
use NilPortugues\MessageBus\EventBus\Contracts\EventHandler;

final class SendWelcomeEmailHandler implements EventHandler
{
    private $emailProvider;
    
    public function __construct($emailProvider)
    {
        $this->emailProvider = $emailProvider;
    }
        
    public function __invoke(UserRegistered $event)
    {
        $this->guard($event);        
        $this->emailProvider->send('welcome_email', $event->getEmail());        
    }
     
    public static function subscribedTo() : string
    {
        return UserRegistered::class;
    }
}


use NilPortugues\MessageBus\EventBus\Contracts\Event;
use NilPortugues\MessageBus\EventBus\Contracts\EventHandler;

final class SetupUserAccountHandler implements EventHandler
{
    private $userFriendsRepository;
    private $userCreditsRepository;
    
    public function __construct($userFriendsRepository, $userCreditsRepository)
    {
        $this->userFriendsRepository = $userFriendsRepository;
        $this->userCreditsRepository = $userCreditsRepository;
    }
        
    public function __invoke(UserRegistered $event)
    {      
        $this->userFriendsRepository->add(new UserFriendsCollection($event->getUserId(), []));        
        $this->userCreditsRepository->add(new UserCredits($event->getUserId(), new Credits(0));        
    }   
        
    public static function subscribedTo() : string
    {
        return UserRegistered::class;
    }
}


use NilPortugues\MessageBus\EventBus\Contracts\Event;
use NilPortugues\MessageBus\EventBus\Contracts\EventHandler;
use NilPortugues\MessageBus\EventBus\Contracts\EventHandlerPriority;

final class SetupUserAccountHandler implements EventHandler, EventHandlerPriority
{
   //same as before...
   
   public static function priority() : int
   {
        return EventHandlerPriority::MAX_PRIORITY;
   }
}


use NilPortugues\MessageBus\EventBus\Contracts\Event;
use NilPortugues\MessageBus\EventBus\Contracts\EventHandler;
use NilPortugues\MessageBus\EventBus\Contracts\EventHandlerPriority;

final class SendWelcomeEmailHandler implements EventHandler, EventHandlerPriority
{
   //same as before...
   
   public static function priority() : int
   {
        return EventHandlerPriority::MAX_PRIORITY - 1;
   }
}


//...your other registered classes

$container['UserFriendRepository'] = function($container) {    
     return []; //your repository
};

$container['UserCreditsRepository'] = function($container) {    
     return []; //your repository
};

$container['EmailProvider'] = function($container) {    
     return []; //your email provider
};

$container['SetupUserAccountHandler'] = function($container) {    
    return new SetupUserAccountHandler(
        $container->get('UserFriendRepository'),
        $container->get('UserCreditsRepository')
    );
};
$container['SendWelcomeEmailHandler'] = function($container) {
    return new SendWelcomeEmailHandler($container->get('EmailProvider');
};


//...your other registered classes

$container['EventTranslator'] = function($container) {
    $handlers = [
       SendWelcomeEmailHandler::class,
       SetupUserAccountHandler::class,
    ];

    return new \NilPortugues\MessageBus\EventBus\Translator\EventFullyQualifiedClassNameStrategy($handlers);
};

$container['EventHandlerResolver'] = function($container) {
    return new \NilPortugues\MessageBus\EventBus\Resolver\PsrContainerResolver($container);
};

$container['EventBusMiddleware'] = function($container) {
    return new \NilPortugues\MessageBus\EventBus\EventBusMiddleware(
        $container->get('EventTranslator'),
        $container->get('EventHandlerResolver'),
    );
};

$container['EventBus'] = function($container) {
    return new \NilPortugues\MessageBus\EventBus\EventBus([  
        $container->get('EventBusMiddleware'),
    ]);
};


//...your other registered classes

$container['LoggerEventBusMiddleware'] = function($container) {
    return new \NilPortugues\MessageBus\EventBus\LoggerEventBusMiddleware(
        $container->get('Monolog')
    );
};

//Update the EventBus with the LoggerEventBusMiddleware
$container['EventBus'] = function($container) {
    return new \NilPortugues\MessageBus\EventBus\EventBus([
        $container->get('LoggerEventBusMiddleware'),
        $container->get('EventBusMiddleware'),
    ]);
};


$eventBus = $container->get('EventBus');
$Event = new GetUser(1):
$userEventResponse = $eventBus($Event);