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

https://github.com/willavelar/php-design-pattern-behavioral-chain-of-responsibility

a simple php example about the behavioral pattern: Chain of Responsibility
https://github.com/willavelar/php-design-pattern-behavioral-chain-of-responsibility

behavioral-patterns chain-of-responsibility design-patterns php

Last synced: 3 months ago
JSON representation

a simple php example about the behavioral pattern: Chain of Responsibility

Awesome Lists containing this project

README

          

## Chain of Responsibility

Chain of Responsibility is behavioral design pattern that allows passing request along the chain of potential handlers until one of them handles request.

-----

We need to create a discount calculator. With this we will have our budget with value and item and it will show the discount depending on the value of the parameters
### The problem

If we do it this way, we have the problem: With each new discount we will have to modify the file by adding another “if”, which can generate additional bugs.

```php
items > 5) {
return $budget->value * 0.1;
}

if ($budget->value > 500) {
return $budget->value * 0.05;
}

return 0;
}
}
```

### The solution

Now, using the Chain of Responsibility pattern, we create an abstract class so that new discounts can be classes and what is the next discount to be calculated passed by reference, thus forming a chain where the discounts should go, and we make a class without discount for the end of this chain.

```php
nextDiscount = $nextDiscount;
}

abstract public function calc(Budget $budget): float;

}
```
```php
items > 5) {
return $budget->value * 0.1;
}

return $this->nextDiscount->calc($budget);
}
}
```
```php
value > 500) {
return $budget->value * 0.05;
}

return $this->nextDiscount->calc($budget);
}
}
```
```php
calc($budget);
}
}
```
-----

### 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
php right/test.php
```