PHP code example of vantukh-kolya / rabbitmq-client

1. Go to this page and download the library: Download vantukh-kolya/rabbitmq-client 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/ */

    

vantukh-kolya / rabbitmq-client example snippets


use App\RabbitMq\Consumers\ConsumedMessageTypeFactory;
use Illuminate\Queue\Jobs\JobName;
use VantukhKolya\RabbitMqClient\Queue\Jobs\RabbitMQJob;
use Illuminate\Support\Facades\Log;

class JobHandler extends RabbitMQJob
{
    public function fire()
    {
        $payload = $this->payload();
        if (!empty($payload['job'])) {
            [$class, $method] = JobName::parse($payload['job']);
            ($this->instance = $this->resolve($class))->{$method}($this, $payload['data']);
        } else {
            if (!empty($payload['msgType'])) {
                $messageType = ConsumedMessageTypeFactory::create($payload['msgType']);
                if ($messageType) {
                    $this->instance = $messageType;
                    $messageType->handle($this);
                } else {
                    Log::error('Unknown message type ' . $payload['msgType']);
                }
            }
        }
        $this->delete();
    }

    protected function failed($e)
    {
        $payload = $this->payload();
        if (!empty($payload['job'])) {
            [$class, $method] = JobName::parse($payload['job']);
            if (method_exists($this->instance = $this->resolve($class), 'failed')) {
                $this->instance->failed($payload['data'], $e, $payload['uuid'] ?? '');
            }
        }
    }

}

use VantukhKolya\RabbitMqClient\Core\MessageTypeInterface;
use VantukhKolya\RabbitMqClient\Queue\Jobs\RabbitMQJob;

class ProductViewed implements MessageTypeInterface
{
    public function handle(RabbitMQJob $job): void
    {
        $messagePayload = $job->payload();
        if (isset($messagePayload['data']['product_code'])) {
            $product = $this->entityManager->find(Product::class, $messagePayload['data']['product_code']);
            if ($product) {
                $product->incrementViewCount();
                $this->entityManager->flush();
            }
        }
    }
}