Bags/Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values.
composer r ghosty/bag
This way you can create a new object of type Bag
// app/Controllers/TestController.php
namespace App\Controllers;
use Ghosty\Component\Bag\Bag;
class TestController
{
public function show()
{
$Bag = new Bag(['1', '2', '3']);
}
}
The all method returns an array of all elements of Bag
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
...
$Elements = $Bag->all();
}
}
The get method returns a Bag element by key
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
...
$Element = $Bag->get('1'); // '2'
}
}
The add method adds a new element by key
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
...
$Bag->add('3', '4');
$Elements = $Bag->all(); // ['1', '2', '3', '4']
}
}
The replace method replaces all Bag elements with new ones
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
...
$Bag->replace(['6', '12']);
$Elements = $Bag->all(); // ['6', '12']
}
}
The has method returns true if the element with the passed key exists in the Bag, otherwise the method returns false
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
...
$Elements = $Bag->all(); // ['6', '12']
$Has = $Bag->has('0'); // true
$Has = $Bag->has('12'); // false
}
}
The remove method removes a Bag element by key
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
...
$Elements = $Bag->all(); // ['6', '12']
$Elements = $Bag->remove('0')->all(); // ['12']
}
}
The count method returns the number of Bag elements, you can also use the standard PHP count method by passing an object of the Bag class to it
// app/Controllers/TestController.php
namespace App\Controllers;
class TestController
{
public function show()
{
...
$Elements = $Bag->all(); // ['12']
$Count = $Bag->count(); // 1
$Count = count($Bag); // 1
}
}
Thanks to the AbstractBag class, you can create your own Bag class thanks to abstract class inheritance.
You can also override methods or write new ones in your class
// app/Bags/TestBag.php
namespace App\Bags;
use Ghosty\Component\Bag\AbstractBag;
class TestBag extends AbstractBag
{
/**
*@param string $value String value
*/
#[\Override]
public function add(string $key, mixed $value): static
{
if(!is_string($value))
{
throw new \Exception("Error");
}
return parent::add($key, $value);
}
}