在领域驱动设计(DDD)中,用例(Use Case)通常表示应用程序的业务逻辑或服务层。用例的职责是协调领域对象以实现特定的业务功能。关于用例是否可以返回实体实例,这取决于具体的设计和应用场景。
假设你有一个简单的电商系统,其中包含订单(Order)实体和一个创建订单的用例。
class Order
{
private $id;
private $items;
private $totalAmount;
public function __construct($id, $items, $totalAmount)
{
$this->id = $id;
$this->items = $items;
$this->totalAmount = $totalAmount;
}
// 领域逻辑方法
public function addItem($item)
{
$this->items[] = $item;
$this->totalAmount += $item->price;
}
// Getter方法
public function getId()
{
return $this->id;
}
public function getItems()
{
return $this->items;
}
public function getTotalAmount()
{
return $this->totalAmount;
}
}
class CreateOrderUseCase
{
private $orderRepository;
public function __construct(OrderRepository $orderRepository)
{
$this->orderRepository = $orderRepository;
}
public function execute($orderData)
{
// 创建订单实体
$order = new Order($orderData['id'], $orderData['items'], $orderData['totalAmount']);
// 保存订单
$this->orderRepository->save($order);
// 返回DTO而不是实体
return new OrderDTO($order->getId(), $order->getItems(), $order->getTotalAmount());
}
}
class OrderDTO
{
public $id;
public $items;
public $totalAmount;
public function __construct($id, $items, $totalAmount)
{
$this->id = $id;
$this->items = $items;
$this->totalAmount = $totalAmount;
}
}
领取专属 10元无门槛券
手把手带您无忧上云