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
- Host: GitHub
- URL: https://github.com/willavelar/php-design-pattern-behavioral-chain-of-responsibility
- Owner: willavelar
- Created: 2023-09-17T18:04:40.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2023-09-17T23:00:37.000Z (about 2 years ago)
- Last Synced: 2025-03-03T02:45:04.376Z (7 months ago)
- Topics: behavioral-patterns, chain-of-responsibility, design-patterns, php
- Language: PHP
- Homepage:
- Size: 7.81 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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 problemIf 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
 
```bash
composer install
``````bash
php wrong/test.php
php right/test.php
```