PHP code example of zack / saga
1. Go to this page and download the library: Download zack/saga 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/ */
zack / saga example snippets
use Symfony\Component\EventDispatcher\EventDispatcher;
use Zack\Saga\Processor;
use Zack\Saga\SagaInterface;
class LoginSaga implements SagaInterface
{
public function run(): \Generator
{
// Wait for the 'acme.user.login' event.
$event = yield take('acme.user.login');
// Get user from given ID.
$user = UserProvider::find($event->getUserId());
if ($user === null) {
// Redirect to login page.
yield dispatch('acme.router.redirect', new RedirectEvent('/login'));
return;
}
// Create session.
yield dispatch('acme.user.session', new UserSessionEvent($user));
// Redirect to dashboard page.
yield dispatch('acme.router.redirect', new RedirectEvent('/login'));
// Fork saga for taking user logout event.
yield fork(new LogoutSaga());
}
}
$eventDispatcher = new EventDispatcher();
// Create a default Processor.
$processor = Processor::create($eventDispatcher);
$processor->run(new LoginSaga());
$eventDispatcher->dispatch('acme.user.login', new LoginEvent(1));