خدمة الطلبات التي تفعل كل شيءThe order service that does everything
متجر إلكتروني: عند إتمام الطلب نحسب المجموع، نحفظ الطلب، ونرسل بريد التأكيد. كل ذلك في دالة واحدة.An online store: placing an order computes the total, saves the order and emails a confirmation. All in one method.
قبلBefore
class OrderService {
placeOrder(cart, user) {
// 1) business rule
const total = cart.items.reduce((sum, i) => sum + i.price, 0);
// 2) database
db.query('INSERT INTO orders ...', [user.id, total]);
// 3) email
smtp.send(user.email, 'Order confirmed', `Total: ${total}`);
}
}
class OrderService
{
public function placeOrder(Cart $cart, User $user): void
{
// 1) business rule
$total = array_sum(array_column($cart->items, 'price'));
// 2) database
DB::insert('INSERT INTO orders ...', [$user->id, $total]);
// 3) email
mail($user->email, 'Order confirmed', "Total: $total");
}
}
class OrderService
{
public void PlaceOrder(Cart cart, User user)
{
// 1) business rule
var total = cart.Items.Sum(i => i.Price);
// 2) database
db.Execute("INSERT INTO orders ...", user.Id, total);
// 3) email
smtp.Send(user.Email, "Order confirmed", $"Total: {total}");
}
}
class OrderService:
def place_order(self, cart, user):
# 1) business rule
total = sum(item.price for item in cart.items)
# 2) database
db.execute("INSERT INTO orders ...", (user.id, total))
# 3) email
smtp.send(user.email, "Order confirmed", f"Total: {total}")
- اسم الصنف فيه Manager أو Service ويكبر بلا حدود.The class is called Manager or Service and keeps growing.
- أشخاص من فرق مختلفة يعدّلون نفس الملف.People from different teams edit the same file.
بعدAfter
class OrderService {
constructor(orders, mailer) {
this.orders = orders;
this.mailer = mailer;
}
placeOrder(cart, user) {
const total = cart.total();
this.orders.save(user.id, total); // OrderRepository: database only
this.mailer.orderConfirmed(user, total); // OrderMailer: email only
}
}
class OrderService
{
public function __construct(
private OrderRepository $orders,
private OrderMailer $mailer,
) {}
public function placeOrder(Cart $cart, User $user): void
{
$total = $cart->total();
$this->orders->save($user->id, $total); // database only
$this->mailer->orderConfirmed($user, $total); // email only
}
}
class OrderService(OrderRepository orders, OrderMailer mailer)
{
public void PlaceOrder(Cart cart, User user)
{
var total = cart.Total();
orders.Save(user.Id, total); // database only
mailer.OrderConfirmed(user, total); // email only
}
}
class OrderService:
def __init__(self, orders, mailer):
self.orders = orders
self.mailer = mailer
def place_order(self, cart, user):
total = cart.total()
self.orders.save(user.id, total) # OrderRepository: database only
self.mailer.order_confirmed(user, total) # OrderMailer: email only
- تغيير البريد لا يلمس كود قاعدة البيانات.Changing the email never touches the database code.
- كل جزء يُختبر وحده.Each part can be tested on its own.