https://github.com/willavelar/php-design-pattern-behavioral-strategy
a simple php example about the behavioral pattern: Strategy
https://github.com/willavelar/php-design-pattern-behavioral-strategy
behavioral-patterns design-patterns php strategy
Last synced: about 1 year ago
JSON representation
a simple php example about the behavioral pattern: Strategy
- Host: GitHub
- URL: https://github.com/willavelar/php-design-pattern-behavioral-strategy
- Owner: willavelar
- Created: 2023-08-28T20:14:58.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-09-17T19:40:41.000Z (over 2 years ago)
- Last Synced: 2025-01-13T14:19:13.626Z (over 1 year ago)
- Topics: behavioral-patterns, design-patterns, php, strategy
- Language: PHP
- Homepage:
- Size: 4.88 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Strategy
Strategy is a behavioral pattern, often used when we have rules for a particular activity that may contain a lot of logic, it organizes and separates the use of these logics, standardizing the usability of classes so that new implementations can be added in the future without much change in the use of a particular class of action.
-----
We need to create a tax calculator. With this, we will have our budget and it will show the specific amount after calculating the taxes.
### The problem
If we do it this way, we have two problems: we are dependent on a string parameter with the name of the tax. If it is passed incorrectly, an error will be returned. In addition, with each new tax, we will have to modify the file by adding another "if", which can generate additional bugs.
```php
value * 0.1;
case "ISS":
return $budget->value * 0.06;
}
}
}
```
### The solution
Now, using the Strategy pattern, we create an interface that serves as a contract for all taxes, with a standardized calculation method. Each new tax just needs to create a new file that will be called when referring to it.
```php
value * 0.1;
}
}
```
```php
value * 0.06;
}
}
```
```php
calculateTax($budget);
}
}
```
-----
### Installation for test
 
```bash
composer install
```
```bash
php wrong/test.php
php right/test.php
```