Я создаю oop-систему в php и хотел бы внедрить в нее больше шаблонов наблюдателей, поскольку у меня сильная связь между моими классами, которую я хочу сократить.
мой вопрос такой.
в отношении наилучшей практики в дизайне для этого шаблона, можно ли одному классу добавить наблюдателя в другой класс, с которым этот класс работает.
или я должен держать наблюдателя, добавляющего к самому верхнему уровню цепи?
пример: (предположим, что другие методы, вызываемые, но не включенные в класс, существуют, но не важны для этого примера.)
class orderItem extends observable {
public function pick($qty, $user){
$this->setUser($user);
$position = new position($this->getPositionID());
$position->addObserver(new ProductObserver()); // is this the best option ? ?
$position->setQty($position->getQty() - $qty);
$position->save();
$this->notify(self::EVENT_PICK); // notify observers
}
}
class orderProductObserver implements observer {
public function update($orderitem){
$position = new position($orderitem->getPositionID());
$product = new product($position->getProductID());
if($product->getQty() < $product->getMinimum()) {
$alert = new minProductAlert($product);
}
}
}
class ProductObserver implements observer {
public function update($position){
$product = new product($position->getProductID());
if($product->getQty() < $product->getMinimum()) {
$alert = new minProductAlert($product);
}
}
}
$order = new orderItem(123);
$order->addObserver(new orderProductObserver()); // or is this the best option ??
$order->pick(2, 'bill');
Или же, если оба метода неверны, я очень заинтересован в вашей информации.
будет ли этот пример наиболее идеальным, если удалить зависимость между элементом порядка и позицией?
class OrderItem extends Observable {
public function pick($qty, $user){
$this->setUser($user);
$this->setPickedQty($qty);
$this->save();
$this->notify(self::EVENT_PICK); // notify observers
}
}
class OrderItemPickObserver implements Observer {
public function update($orderitem){
$position = new Position($orderitem->getPositionID());
$position->addObserver(new ProductPositionObserver());
$position->setQty($position->getQty() - $orderItem->getPickedQty());
$position->save();
}
}
class ProductPositionObserver implements Observer {
public function update($position){
$product = new product($position->getProductID());
if($product->getQty() < $product->getMinimum()) {
$alert = new minProductAlert($product);
}
}
}
$pickQty = 2;
$orderitem = new OrderItem(123);
$position = new Position($orderitem->getPositionID());
if($position->getQty() >= $pickQty)
{
$orderitem->addObserver(new OrderItemPickObserver()); // or is this the best option ??
$orderitem->pick($pickQty, 'bill');
}