Field Manual Brokerage / Linux / Laravel
← Laravel

app/Services/OrderService.php

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

What it is

Complete brokerage practice file. The Assemble project page lists every file in order.

When to use it

Paste the complete file at this path. Names and paths are case-sensitive on Linux.

Syntax

mkdir -p 'app/Services'
# Paste the Example below into app/Services/OrderService.php

Example

<?php

declare(strict_types=1);

namespace App\Services;

use App\Exceptions\ExchangeException;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;

class OrderService
{
    public function __construct(private readonly ExchangeClient $exchange)
    {
    }

    public function place(array $attributes): Order
    {
        $order = DB::transaction(fn (): Order => Order::create([
            ...$attributes,
            'client_order_id' => (string) Str::uuid(),
            'status' => 'pending',
        ]));

        // The HTTP call must happen outside a database transaction.
        try {
            $response = $this->exchange->submitOrder([
                ...$attributes,
                'client_order_id' => $order->client_order_id,
            ]);
            $result = ['status' => 'accepted', 'exchange_order_id' => $response['exchange_order_id']];
        } catch (ExchangeException $exception) {
            $result = $exception->httpStatus === 422
                ? ['status' => 'rejected', 'rejection_message' => $exception->getMessage()]
                : ['status' => 'unknown'];
            $this->saveResult($order, $result);
            if ($exception->httpStatus === 503) {
                throw new ExchangeException('Order status is unconfirmed. Do not submit it again; contact the broker.', 503);
            }
            throw $exception;
        }

        return $this->saveResult($order, $result);
    }

    private function saveResult(Order $order, array $result): Order
    {
        try {
            return DB::transaction(function () use ($order, $result): Order {
                $order->update($result);
                return $order;
            });
        } catch (Throwable $exception) {
            Log::error('Could not save order result', [
                'order_id' => $order->id,
                'client_order_id' => $order->client_order_id,
            ]);
            throw $exception;
        }
    }
}

Common mistakes

Use the setup runbook first. Adapt provisional API assumptions to the supplied contract. Merge into supplied applications; do not duplicate the orders migration.

Related topics

API contract: change these points first