Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/willavelar/php-design-pattern-behavioral-iterator
a simple php example about the behavioral pattern: Iterator
https://github.com/willavelar/php-design-pattern-behavioral-iterator
behavioral-patterns design-patterns iterator php
Last synced: 6 days ago
JSON representation
a simple php example about the behavioral pattern: Iterator
- Host: GitHub
- URL: https://github.com/willavelar/php-design-pattern-behavioral-iterator
- Owner: willavelar
- Created: 2023-10-31T19:47:11.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2023-10-31T20:18:34.000Z (about 1 year ago)
- Last Synced: 2023-10-31T22:24:20.418Z (about 1 year ago)
- Topics: behavioral-patterns, design-patterns, iterator, php
- Language: PHP
- Homepage:
- Size: 1.95 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Iterator
Iterator is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.).
-----
We need to create a list of budgets and then show information about them.
### The problem
This way, by grouping via array, we can place other types of information that will not be part of the budget, thus creating gaps in our code.
```php
items = 7;
$budget1->value = 1500.75;$budget2 = new Budget();
$budget2->items = 3;
$budget2->value = 150;$budget3 = new Budget();
$budget3->items = 5;
$budget3->value = 1350;$budgetList = [
$budget1,
$budget2,
$budget3
];foreach ($budgetList as $budget) {
echo "Value: ". $budget->value . PHP_EOL;
echo "Items: ". $budget->items . PHP_EOL;echo PHP_EOL;
}
```### The solution
Now, using the Itarator pattern, we create an object that is a list of budgets, which only accepts budgets, and then we make it traversable by the PHP Iterator.
```php
budget[] = $budget;
}public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->budget);
}
}
```
```php
items = 7;
$budget1->value = 1500.75;$budget2 = new Budget();
$budget2->items = 3;
$budget2->value = 150;$budget3 = new Budget();
$budget3->items = 5;
$budget3->value = 1350;$budgetList = new BudgetList();
$budgetList->addBudget($budget1);
$budgetList->addBudget($budget2);
$budgetList->addBudget($budget3);foreach ($budgetList as $budget) {
echo "Value: ". $budget->value . PHP_EOL;
echo "Items: ". $budget->items . PHP_EOL;echo PHP_EOL;
}
```-----
### 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
```