Задание 1
Приведи в порядок легаси-контроллер Yii2: вынеси логику в сервис, не зависящий от фреймворка, добавь типы и тесты. Объясни, почему такой сервис потом легко перенести в Laravel.
<?php
// Типичный контроллер Yii2 из проекта 2017 года
class OrderController extends Controller
{
public function actionCreate()
{
$request = Yii::$app->request;
$items = $request->post('items');
$promoCode = $request->post('promo_code');
if (empty($items)) {
Yii::$app->session->setFlash('error', 'Корзина пуста');
return $this->redirect(['cart/index']);
}
$transaction = Yii::$app->db->beginTransaction();
try {
$order = new Order();
$order->user_id = Yii::$app->user->id;
$order->status = Order::STATUS_NEW;
$order->created_at = time();
$total = 0;
foreach ($items as $item) {
$product = Product::findOne($item['product_id']);
if (!$product) {
throw new Exception('Product not found');
}
if ($product->stock < $item['qty']) {
throw new Exception('Not enough stock');
}
$product->stock -= $item['qty'];
$product->save();
$total += $product->price * $item['qty'];
}
if ($promoCode) {
$promo = Promo::find()->where(['code' => $promoCode])->one();
if ($promo && $total >= $promo->min_total) {
$total = $total - ($total * $promo->percent / 100);
}
}
if ($total >= 5000) {
$delivery = 0;
} else {
$delivery = 400;
}
$total += $delivery;
$order->total = $total;
$order->save();
foreach ($items as $item) {
$orderItem = new OrderItem();
$orderItem->order_id = $order->id;
$orderItem->product_id = $item['product_id'];
$orderItem->qty = $item['qty'];
$orderItem->save();
}
$transaction->commit();
Yii::$app->mailer->compose('order-created', ['order' => $order])
->setTo(Yii::$app->user->identity->email)
->send();
return $this->redirect(['order/view', 'id' => $order->id]);
} catch (Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', $e->getMessage());
return $this->redirect(['cart/index']);
}
}
}
Решение
<?php
declare(strict_types=1);
/*
ПЛАН
1. Чистая логика расчёта → отдельный класс без Yii
2. Сценарий → сервис, зависящий от интерфейсов
3. Реализации интерфейсов → адаптеры к Yii
4. Контроллер → тонкий: разобрать, вызвать, отдать
5. Тесты на логику — без фреймворка и БД
*/
// ══════════ 1. ЧИСТАЯ ЛОГИКА (без Yii) ══════════
// src/Domain/Order/Pricing.php
namespace App\Domain\Order;
final readonly class OrderLine
{
public function __construct(
public int $productId,
public string $title,
public int $price, // копейки
public int $qty,
public int $availableStock,
) {}
public function subtotal(): int
{
return $this->price * $this->qty;
}
public function isAvailable(): bool
{
return $this->availableStock >= $this->qty;
}
}
final readonly class Promo
{
public function __construct(
public string $code,
public float $percent,
public int $minTotal,
public int $maxDiscount,
) {}
public function appliesTo(int $subtotal): bool
{
return $subtotal >= $this->minTotal;
}
public function discountFor(int $subtotal): int
{
return min(
(int) round($subtotal * $this->percent / 100),
$this->maxDiscount,
);
}
}
final readonly class OrderAmounts
{
public function __construct(
public int $subtotal,
public int $discount,
public int $delivery,
public int $total,
) {}
}
/** Ни одного упоминания Yii. Тестируется мгновенно */
final readonly class PricingCalculator
{
public function __construct(
private int $freeDeliveryFrom = 500_000, // копейки
private int $deliveryCost = 40_000,
) {}
/** @param list<OrderLine> $lines */
public function calculate(array $lines, ?Promo $promo = null): OrderAmounts
{
$subtotal = array_reduce(
$lines,
static fn (int $sum, OrderLine $l): int => $sum + $l->subtotal(),
0,
);
$discount = $promo?->appliesTo($subtotal)
? $promo->discountFor($subtotal)
: 0;
$afterDiscount = $subtotal - $discount;
// ВАЖНО: порог бесплатной доставки считается
// ПОСЛЕ скидки. В исходном коде было так же,
// сохраняем поведение
$delivery = $afterDiscount >= $this->freeDeliveryFrom
? 0
: $this->deliveryCost;
return new OrderAmounts(
subtotal: $subtotal,
discount: $discount,
delivery: $delivery,
total: $afterDiscount + $delivery,
);
}
}
// ══════════ 2. ИНТЕРФЕЙСЫ ══════════
namespace App\Domain\Order\Contract;
interface ProductReaderInterface
{
/** @param list<int> $ids @return array<int, OrderLine> */
public function findForOrder(array $ids, array $quantities): array;
}
interface StockWriterInterface
{
/** @param list<OrderLine> $lines @return list<int> недоступные id */
public function decrement(array $lines): array;
}
interface OrderWriterInterface
{
public function create(int $userId, OrderAmounts $amounts, array $lines,
?string $promoCode): int;
}
interface TransactionInterface
{
public function run(callable $fn): mixed;
}
interface MailerInterface
{
public function sendOrderCreated(int $orderId, string $email): void;
}
// ══════════ 3. СЦЕНАРИЙ ══════════
namespace App\Domain\Order;
final class CreateOrderException extends \RuntimeException
{
public function __construct(
string $message,
public readonly string $errorCode,
public readonly array $context = [],
) {
parent::__construct($message);
}
}
final readonly class CreateOrderService
{
public function __construct(
private ProductReaderInterface $products,
private StockWriterInterface $stock,
private OrderWriterInterface $orders,
private PromoReaderInterface $promos,
private TransactionInterface $transaction,
private PricingCalculator $pricing,
private MailerInterface $mailer,
) {}
/**
* @param list<array{product_id: int, qty: int}> $items
*/
public function create(array $items, ?string $promoCode, int $userId,
string $email): int
{
if ($items === []) {
throw new CreateOrderException('Корзина пуста', 'EMPTY_CART');
}
$quantities = [];
foreach ($items as $item) {
$qty = (int) $item['qty'];
if ($qty < 1 || $qty > 99) {
throw new CreateOrderException(
'Некорректное количество', 'INVALID_QTY',
['product_id' => $item['product_id']],
);
}
$quantities[(int) $item['product_id']] = $qty;
}
$lines = $this->products->findForOrder(array_keys($quantities), $quantities);
$missing = array_diff(array_keys($quantities), array_keys($lines));
if ($missing !== []) {
throw new CreateOrderException(
'Товар не найден', 'PRODUCT_NOT_FOUND',
['ids' => array_values($missing)],
);
}
$promo = $promoCode !== null ? $this->promos->findActive($promoCode) : null;
$amounts = $this->pricing->calculate(array_values($lines), $promo);
$orderId = $this->transaction->run(function () use ($lines, $amounts,
$userId, $promoCode) {
// Атомарное списание: гонка невозможна
$unavailable = $this->stock->decrement(array_values($lines));
if ($unavailable !== []) {
throw new CreateOrderException(
'Часть товаров недоступна', 'OUT_OF_STOCK',
['product_ids' => $unavailable],
);
}
return $this->orders->create($userId, $amounts,
array_values($lines), $promoCode);
});
// Письмо ПОСЛЕ коммита: при откате не уйдёт
$this->mailer->sendOrderCreated($orderId, $email);
return $orderId;
}
}
// Ни одного use из Yii. Этот класс работает где угодно
// ══════════ 4. АДАПТЕРЫ К YII ══════════
namespace App\Infrastructure\Yii;
final class YiiTransaction implements TransactionInterface
{
public function run(callable $fn): mixed
{
$transaction = \Yii::$app->db->beginTransaction();
try {
$result = $fn();
$transaction->commit();
return $result;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
}
}
final class ActiveRecordStockWriter implements StockWriterInterface
{
public function decrement(array $lines): array
{
$unavailable = [];
foreach ($lines as $line) {
// Атомарно: условие в самом UPDATE.
// В исходном коде было read-modify-write —
// гонка при одновременных заказах
$affected = \Yii::$app->db->createCommand()
->update(
'product',
['stock' => new \yii\db\Expression('stock - :qty',
[':qty' => $line->qty])],
['and', ['id' => $line->productId],
['>=', 'stock', $line->qty]],
)
->execute();
if ($affected === 0) {
$unavailable[] = $line->productId;
}
}
return $unavailable;
}
}
final class ActiveRecordProductReader implements ProductReaderInterface
{
public function findForOrder(array $ids, array $quantities): array
{
// Один запрос вместо N — в исходном коде
// findOne() вызывался в цикле
$rows = \Product::find()
->where(['id' => $ids, 'is_active' => 1])
->asArray()
->all();
$result = [];
foreach ($rows as $row) {
$id = (int) $row['id'];
$result[$id] = new OrderLine(
productId: $id,
title: $row['title'],
price: (int) $row['price'],
qty: $quantities[$id],
availableStock: (int) $row['stock'],
);
}
return $result;
}
}
final class YiiMailer implements MailerInterface
{
public function sendOrderCreated(int $orderId, string $email): void
{
// Лучше — через очередь, но даже так:
// вынесено из транзакции
\Yii::$app->mailer
->compose('order-created', ['orderId' => $orderId])
->setTo($email)
->send();
}
}
// ══════════ 5. ТОНКИЙ КОНТРОЛЛЕР ══════════
final class OrderController extends \yii\web\Controller
{
private CreateOrderService $createOrder;
public function init(): void
{
parent::init();
// Yii умеет в DI-контейнер
$this->createOrder = \Yii::$container->get(CreateOrderService::class);
}
public function actionCreate(): \yii\web\Response
{
$request = \Yii::$app->request;
try {
$orderId = $this->createOrder->create(
items: (array) $request->post('items', []),
promoCode: $request->post('promo_code'),
userId: (int) \Yii::$app->user->id,
email: \Yii::$app->user->identity->email,
);
} catch (CreateOrderException $e) {
\Yii::$app->session->setFlash('error', $e->getMessage());
\Yii::error([
'message' => $e->getMessage(),
'code' => $e->errorCode,
'context' => $e->context,
], 'order');
return $this->redirect(['cart/index']);
}
return $this->redirect(['order/view', 'id' => $orderId]);
}
}
// ══════════ 6. ТЕСТЫ БЕЗ ФРЕЙМВОРКА ══════════
final class PricingCalculatorTest extends \PHPUnit\Framework\TestCase
{
private PricingCalculator $pricing;
protected function setUp(): void
{
$this->pricing = new PricingCalculator(
freeDeliveryFrom: 500_000,
deliveryCost: 40_000,
);
}
public function test_free_delivery_above_threshold(): void
{
$amounts = $this->pricing->calculate([$this->line(600_000, 1)]);
$this->assertSame(0, $amounts->delivery);
$this->assertSame(600_000, $amounts->total);
}
public function test_discount_pushes_below_free_delivery(): void
{
// Краевой случай, который легко сломать при рефакторинге
$amounts = $this->pricing->calculate(
[$this->line(520_000, 1)],
new Promo('SALE10', 10.0, 0, 1_000_000),
);
$this->assertSame(52_000, $amounts->discount);
$this->assertSame(40_000, $amounts->delivery); // платная!
$this->assertSame(508_000, $amounts->total);
}
public function test_discount_capped_at_max(): void
{
$amounts = $this->pricing->calculate(
[$this->line(10_000_000, 1)],
new Promo('SALE10', 10.0, 0, 300_000),
);
$this->assertSame(300_000, $amounts->discount); // не 1 000 000
}
private function line(int $price, int $qty): OrderLine
{
return new OrderLine(1, 'Товар', $price, $qty, 100);
}
}
// Тест сценария с подставными реализациями
final class CreateOrderServiceTest extends \PHPUnit\Framework\TestCase
{
public function test_rejects_empty_cart(): void
{
$service = $this->makeService();
$this->expectException(CreateOrderException::class);
$this->expectExceptionMessage('Корзина пуста');
$service->create([], null, 1, 'a@b.ru');
}
public function test_does_not_send_mail_when_out_of_stock(): void
{
$mailer = new SpyMailer();
$service = $this->makeService(
stock: new FakeStockWriter(unavailable: [1]),
mailer: $mailer,
);
try {
$service->create([['product_id' => 1, 'qty' => 5]], null, 1, 'a@b.ru');
} catch (CreateOrderException) {}
$this->assertSame(0, $mailer->sentCount);
}
}
/* ══════════ ПОЧЕМУ ЭТО ЛЕГКО ПЕРЕНЕСТИ В LARAVEL ══════════
При переходе МЕНЯЮТСЯ ТОЛЬКО адаптеры:
YiiTransaction → LaravelTransaction
(DB::transaction($fn))
ActiveRecordProductReader → EloquentProductReader
YiiMailer → LaravelMailer (или задача в очереди)
OrderController (Yii) → OrderController (Laravel)
НЕ МЕНЯЕТСЯ:
PricingCalculator — чистая логика
CreateOrderService — сценарий
OrderLine, Promo, OrderAmounts — value objects
Все интерфейсы
Все тесты домена
Это ~70% написанного кода. Перенос — вопрос дней,
а не месяцев.
ЧТО ЕЩЁ УЛУЧШИЛОСЬ ПОПУТНО
1. Убран N+1: findOne() в цикле → один запрос
2. Исправлена гонка при списании остатка:
было read-modify-write, стало атомарный UPDATE
с условием
3. Письмо вынесено из транзакции:
раньше уходило даже при откате
4. Появились типы и строгий режим
5. Ошибки различимы по коду, а не по тексту
6. Расчёт цены покрыт тестами: три найденных
краевых случая раньше никто не проверял
7. Максимальная скидка теперь ограничена
(в исходном коде промокод на 90% при большой сумме
давал скидку без потолка)
ГЛАВНЫЙ ПРИНЦИП
Логика ВНЕ фреймворка переносится.
Логика ВНУТРИ фреймворка — нет.
Это верно для любой миграции, а не только Yii → Laravel.
*/
Приём с интерфейсом TransactionInterface вместо прямого вызова Yii::$app->db — то, что делает сервис переносимым: без него весь сценарий оказывается привязан к фреймворку одной строкой, и переносить приходится всё заново.