PHP code example of butschster / lumen-microservice

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

    

butschster / lumen-microservice example snippets


// bootstrap.php
$app->register(Butschster\Exchanger\Providers\ExchangeServiceProvider::class);

$app->configure('amqp');
$app->configure('microservice');
$app->configure('serializer');

namespace App\Exchange\Point;

use Butschster\Exchanger\Contracts\Exchange\Point as PointContract;
use Psr\Log\LoggerInterface;
use Butschster\Exchanger\Contracts\Exchange\IncomingRequest;

class Point implements PointContract
{
    public function getName(): string
    {
        return 'com.test';
    }

    /**
     * @subject com.test.action.test
     */
    public function testSubject(IncomingRequest $request, LoggerInterface $logger)
    {
        $logger->info(
            sprintf('info [%s]:', $request->getSubject()),
            [$request->getBody()]
        );

        // Response
        $payload = new ...;
        $request->sendResponse($payload);

        // or
        $request->sendEmptyResponse();

        // or
        $request->acknowledge();
    }

    /**
     * @subject com.test.action.test1
     */
    public function anotherTestSubject(IncomingRequest $request, LoggerInterface $logger)
    {
        $payload = new ...;
        $request->sendResponse($payload);
    }
}

use App\Exchange\Point;
use Illuminate\Support\ServiceProvider;
use Butschster\Exchanger\Contracts\Exchange\Point as PointContract;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(PointContract::class, Point::class);
    }
}

use Butschster\Exchanger\Console\Commands\RunMicroservice;

class Kernel extends ConsoleKernel
{
    protected $commands = [
        RunMicroservice::class
    ];
}

use Butschster\Exchanger\Contracts\ExchangeManager;

class UserController {

    public function getUser(ExchangeManager $manager, int $userId)
    {
        $requestPayload = new GetUserByIdPayload($userId);

        $request = $manager->request('com.test.action.test', $requestPayload);
        $user = $request->send(UserPayload::class);

        // You can set delivery mode to persistent
        $user = $request->send(UserPayload::class, true);
    }
}

// User Request Payload

use JMS\Serializer\Annotation\Type;

class GetUserByIdPayload implements \Butschster\Exchanger\Contracts\Exchange\Payload
{
    /** @Type("string") */
    public string $userId;
    public function __construct(string $userId)
    {
        $this->userId = $userId;
    }
}

// User Payload

use JMS\Serializer\Annotation\Type;

class UserPayload implements \Butschster\Exchanger\Contracts\Exchange\Payload
{
    /** @Type("string") */
    public string $id;

    /** @Type("string") */
    public string $username;

    /** @Type("string") */
    public string $email;

    /** @Type("Carbon\Carbon") */
    public \Carbon\Carbon $createdAt;
}

use Illuminate\Http\Request;
use Butschster\Exchanger\Contracts\ExchangeManager;

class UserController {

    public function update(ExchangeManager $manager, Request $request, User $user)
    {
        $payload = new UserPayload();
        $data = $request->validate(...);
        $user->update($data);

        $payload->id = $user->id;
        $payload->username = $user->username;
        ...
        
        $manager->broadcast('com.user.event.updated', $payload);

        // You can set delivery mode to persistent
        $manager->broadcast('com.user.event.updated', $payload, true);
    }
}

// serializer.php
return [
    'mapping' => [
        Domain\User\Entities\User::class => [
            'to' => Payloads\User::class,
            'attributes' => [
                'id' => ['type' => 'string'],
                'username' => ['type' => 'string'],
                'email' => ['type' => 'string'],
                'balance' => ['type' => Domain\Billing\Money\Token::class],
                'createdAt' => ['type' => \Carbon\Carbon::class],
            ]
        ],
        Domain\Billing\Money\Token::class => [
            'to' => Payloads\Billing\Token::class,
            'attributes' => [
                'amount' => ['type' => \Brick\Math\BigDecimal::class],
            ]
        ],
    ],
    // ...
];

use Butschster\Exchanger\Contracts\Serializer\ObjectsMapper;

class UserController {

    public function update(ObjectsMapper $mapper, ExchangeManager $manager, Request $request, Domain\User\Entities\User $user)
    {
        $data = $request->validate(...);
        $user->update($data);
        
        $payload = $mapper->toPayload($user);
        
        $manager->broadcast('com.user.event.updated', $payload);
    }
}

// serializer.php
return [
    'handlers' => [
        Butschster\Exchanger\Jms\Handlers\CarbonHandler::class,
        Infrastructure\Microservice\Jms\Handlers\BigDecimalHandler::class
    ],
    // ..
];

// BigDecimalHandler.php

namespace Infrastructure\Microservice\Jms\Handlers;

use Brick\Math\BigDecimal;
use Butschster\Exchanger\Contracts\Serializer;
use Butschster\Exchanger\Contracts\Serializer\Handler;
use JMS\Serializer\GraphNavigatorInterface;
use JMS\Serializer\Handler\HandlerRegistryInterface;

class BigDecimalHandler implements Handler
{
    public function serialize(Serializer $serializer, HandlerRegistryInterface $registry): void
    {
        $registry->registerHandler(
            GraphNavigatorInterface::DIRECTION_SERIALIZATION,
            BigDecimal::class,
            'json',
            function ($visitor, BigDecimal $value, array $type) {
                return $value->toInt();
            }
        );
    }

    public function deserialize(Serializer $serializer, HandlerRegistryInterface $registry): void
    {
        $registry->registerHandler(
            GraphNavigatorInterface::DIRECTION_DESERIALIZATION,
            BigDecimal::class,
            'json',
            function ($visitor, $value, array $type) {
                return BigDecimal::of($value);
            }
        );
    }
}