https://github.com/willavelar/php-design-pattern-behavioral-observer
a simple php example about the behavioral pattern: Observer
https://github.com/willavelar/php-design-pattern-behavioral-observer
behavioral-patterns design-patterns observer php
Last synced: 7 months ago
JSON representation
a simple php example about the behavioral pattern: Observer
- Host: GitHub
- URL: https://github.com/willavelar/php-design-pattern-behavioral-observer
- Owner: willavelar
- Created: 2023-10-30T19:53:07.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-10-31T19:35:23.000Z (over 2 years ago)
- Last Synced: 2025-03-03T02:45:04.411Z (about 1 year ago)
- Topics: behavioral-patterns, design-patterns, observer, php
- Language: PHP
- Homepage:
- Size: 3.91 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Command
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.
-----
When an order is generated, we need to perform several actions such as storing it in the database, sending it by email, and generating a log.
### The problem
If we need to add more actions after generating order, our function will grow infinitely.
```php
budgetValue = $budgetValue;
$this->items = $items;
$this->customereName = $customereName;
}
public function getBudgetValue(): float
{
return $this->budgetValue;
}
public function getItems(): int
{
return $this->items;
}
public function getCustomereName(): string
{
return $this->customereName;
}
}
```
```php
items = $generateOrder->getItems();
$budget->value = $generateOrder->getBudgetValue();
$order = new Order();
$order->finalizationDate = new \DateTimeImmutable();
$order->customerName = $generateOrder->getCustomereName();
$order->budget = $budget;
new CreateOrderDatabase($order);
new GenerateOrderLog($order);
new SendOrderEmail($order);
}
}
```
```php
actionsAfterGenerateOrder[] = $action;
}
public function execute(GenerateOrder $generateOrder)
{
$budget = new Budget();
$budget->items = $generateOrder->getItems();
$budget->value = $generateOrder->getBudgetValue();
$order = new Order();
$order->finalizationDate = new \DateTimeImmutable();
$order->customerName = $generateOrder->getCustomereName();
$order->budget = $budget;
foreach ($this->actionsAfterGenerateOrder as $action) {
$action->execAction($order);
}
}
}
```
-----
### Installation for test
 
```bash
composer install
```
```bash
php wrong/test.php {budgetValue} {items} {customereName}
php right/test.php {budgetValue} {items} {customereName}
```