https://github.com/linkorb/collection
Super powered collections for PHP
https://github.com/linkorb/collection
Last synced: 3 months ago
JSON representation
Super powered collections for PHP
- Host: GitHub
- URL: https://github.com/linkorb/collection
- Owner: linkorb
- License: mit
- Created: 2017-08-05T08:53:52.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2017-08-05T08:57:34.000Z (almost 8 years ago)
- Last Synced: 2025-01-06T06:43:53.477Z (5 months ago)
- Language: PHP
- Size: 4.88 KB
- Stars: 0
- Watchers: 5
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
Collection
==========This library implements a few helpful collection classes and interfaces.
## TypedArray
This class behaves exactly like an array, but only allows items of a specified type:
```php
$monkeys = new \Collection\TypedArray(Monkey::class);$monkeys->add(new Monkey('Bubbles')); // OK
$monkeys[] = new Monkey('King Kong'); // OK
$monkeys->add(new Snake('Kaa')); // throws CollectionException// You can iterate over the collection
foreach ($monkeys as $monkey) {
echo $monkey->getName();
}
```## Adding items to a collection
You can add items in the regular array way:
```php
$monkeys[] = new Monkey('King Kong');
```Or use the `add()` method
```php
$monkeys->add(new Monkey('King Kong'));
```## Identifiable interface
The `Identifiable` class forces a class to implement the `identifier()` method. This method
should return a key that makes this instance of a class unique.
Maybe it's an ID, a key, a name, or an email address, as long as it uniquely identifies the item.```php
class Monkey implements \Collection\Identifiable
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}public function identifier()
{
return $this->name;
}
}
```When adding instances of this class to a collection, the identifier will automatically be used as the key:
```php
$monkeys = new \Collection\TypedArray(Monkey::class);$m1 = new Monkey('George');
$m2 = new Monkey('Koko');$monkeys[] = $m1; // array contains 1 item
$monkeys[] = $m2; // array contains 2 item
$monkeys[] = $m2; // array still contains 2 items!
$monkeys->add($m2); // array still contains 2 items!$monkeys->hasKey('George')); // returns true
$monkeys->hasKey('King Kong')); // returns false
isset($monkeys['George']); // returns true
```## Using collections in classes
```php
class Zoo
{
protected $monkeys;public function __construct()
{
$this->monkeys = new Collection\TypedArray(Monkey::class);
}public function getMonkeys()
{
return $this->monkeys;
}
}$zoo = new Zoo();
$zoo->getMonkeys()->add(new Monkey('Koko');foreach ($zoo->getMonkeys() as $monkey() {
}
```