An open API service indexing awesome lists of open source software.

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

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

![PHP Version Support](https://img.shields.io/badge/php-7.4%2B-brightgreen.svg?style=flat-square) ![Composer Version Support](https://img.shields.io/badge/composer-2.2.9%2B-brightgreen.svg?style=flat-square)

```bash
composer install
```

```bash
php wrong/test.php {budgetValue} {items} {customereName}
php right/test.php {budgetValue} {items} {customereName}
```