Реорганизация кода в проекте магазина
Условие задачи
Есть проект магазин, который включает несколько классов для продуктов и их репозиториев. Доступно две операции: резервирование продукта и пополнение. Реорганизовать код с точки зрения последующих изменений, инкапсуляции.
phpnamespace MyAwesomeShop;
final readonly class ProductId {}
final class NotEnoughProductInStock extends \Exception {}
interface ProductRepository
{
public function get(ProductId $productId): Product;
public function save(Product $inventory): void;
}
final class Product
{
public int $quantity = 0;
public function __construct(
public readonly ProductId $productId,
public string $title,
public string $description = '',
) {}
}
final readonly class InventoryService
{
public function __construct(
private ProductRepository $repository,
) {}
public function reserve(ProductId $productId, int $quantity): void
}
$inventory = $this->repository->get($productId);
if ($inventory->quantity < $quantity) {
throw new NotEnoughProductInStock();
}
$inventory->quantity -= $quantity;
$this->repository->save($inventory);
}
public function replenish(ProductId $productId, int $quantity): void
{
$inventory = $this->repository->get($productId);
$inventory->quantity += $quantity;
$this->repository->save($inventory);
}