adamnicholson / bag
A simple parameter bag to make working with arrays easier
Installs: 25 505
Dependents: 1
Suggesters: 0
Security: 0
Stars: 2
Watchers: 1
Forks: 1
Open Issues: 0
Requires
- php: >=8.0
Requires (Dev)
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-10-15 15:28:14 UTC
README
Bag is a simple parameter bag class to make working with arrays easier.
Motivation
Boilerplate isset
calls whenever working with arrays can be a pain.
function foo (array $data) { if (!isset($data['status']) || !isset($data['data']['foo'])) || $data['status'] !== 'success') { return false; } return $data['data']['foo']; } // vs function bar (array $data) { $data = new Bag($data); if ($bag->get('status') !== 'success') { return false; } return $bag->get('data.foo'); }
Note:
isset
boilerplate will hopefully be much less of a chore in PHP7 with the isset ternary operator
Usage
$array = [ 'foo' => 'bar', 'hello' => 'world', 'items' => [ 'first' => 'fizz', 'second' => 'buzz' ] ]; $bag = new Adam\Bag\Bag($array); // Get a value by key $bag->get('foo'); // string "bar" // Set some value by key $bag->set('fizz', 'buzz'); // Return a default value if the key is not set $bag->get('ziff'); // null $bag->get('ziff', 'my_default_value'); // string "my_default_value" // Use dot notation for multidimensional arrays $bag->get('items.first'); // string "fizz" $bag->set('items.third', 'foovalue'); // Get the value of an item and then remove it $bag->pluck('foo'); // string "bar" $bag->get('foo'); // null // Get the raw data $bag->all(); // array // Empty the data $bag->flush(); // Or just use it like an array $bag['foo'] = 'bar'; $bag['foo']; // string "bar" $bag->get('foo'); // string "bar"
Contributing
We welcome any contributions to this project. They can be made via GitHub issues or pull requests.
License
This project is licensed under the MIT License - see the LICENSE.txt
file for details
Author
Adam Nicholson - adamnicholson10@gmail.com