| 1 |
# chillerlan/php-settings-container |
| 2 |
|
| 3 |
A container class for settings objects - decouple configuration logic from your application! Not a DI container. |
| 4 |
- [`SettingsContainerInterface`](https://github.com/chillerlan/php-settings-container/blob/main/src/SettingsContainerInterface.php) provides fancy [property hooks](https://wiki.php.net/rfc/property-hooks) for PHP < 8.4. |
| 5 |
|
| 6 |
[![PHP Version Support][php-badge]][php] |
| 7 |
[![version][packagist-badge]][packagist] |
| 8 |
[![license][license-badge]][license] |
| 9 |
[![Continuous Integration][gh-action-badge]][gh-action] |
| 10 |
[![Coverage][coverage-badge]][coverage] |
| 11 |
[![Codacy][codacy-badge]][codacy] |
| 12 |
[![Packagist downloads][downloads-badge]][downloads] |
| 13 |
|
| 14 |
[php-badge]: https://img.shields.io/packagist/php-v/chillerlan/php-settings-container?logo=php&color=8892BF |
| 15 |
[php]: https://www.php.net/supported-versions.php |
| 16 |
[packagist-badge]: https://img.shields.io/packagist/v/chillerlan/php-settings-container.svg?logo=packagist |
| 17 |
[packagist]: https://packagist.org/packages/chillerlan/php-settings-container |
| 18 |
[license-badge]: https://img.shields.io/github/license/chillerlan/php-settings-container.svg |
| 19 |
[license]: https://github.com/chillerlan/php-settings-container/blob/main/LICENSE |
| 20 |
[coverage-badge]: https://img.shields.io/codecov/c/github/chillerlan/php-settings-container.svg?logo=codecov |
| 21 |
[coverage]: https://codecov.io/github/chillerlan/php-settings-container |
| 22 |
[codacy-badge]: https://img.shields.io/codacy/grade/bd2467799e2943d2853ce3ebad5af490/main?logo=codacy |
| 23 |
[codacy]: https://app.codacy.com/gh/chillerlan/php-settings-container/dashboard?branch=main |
| 24 |
[downloads-badge]: https://img.shields.io/packagist/dt/chillerlan/php-settings-container.svg?logo=packagist |
| 25 |
[downloads]: https://packagist.org/packages/chillerlan/php-settings-container/stats |
| 26 |
[gh-action-badge]: https://img.shields.io/github/actions/workflow/status/chillerlan/php-settings-container/ci.yml?branch=main&logo=github |
| 27 |
[gh-action]: https://github.com/chillerlan/php-settings-container/actions/workflows/ci.yml?query=branch%3Amain |
| 28 |
|
| 29 |
## Documentation |
| 30 |
|
| 31 |
### Installation |
| 32 |
**requires [composer](https://getcomposer.org)** |
| 33 |
|
| 34 |
*composer.json* (note: replace `dev-main` with a [version constraint](https://getcomposer.org/doc/articles/versions.md#writing-version-constraints), e.g. `^3.0` - see [releases](https://github.com/chillerlan/php-settings-container/releases) for valid versions) |
| 35 |
```json |
| 36 |
{ |
| 37 |
"require": { |
| 38 |
"php": "^8.1", |
| 39 |
"chillerlan/php-settings-container": "dev-main" |
| 40 |
} |
| 41 |
} |
| 42 |
``` |
| 43 |
|
| 44 |
Profit! |
| 45 |
|
| 46 |
## Usage |
| 47 |
|
| 48 |
The `SettingsContainerInterface` (wrapped in`SettingsContainerAbstract`) provides plug-in functionality for immutable object properties and adds some fancy, like loading/saving JSON, arrays etc. |
| 49 |
It takes an `iterable` as the only constructor argument and calls a method with the trait's name on invocation (`MyTrait::MyTrait()`) for each used trait. |
| 50 |
|
| 51 |
A PHPStan ruleset to exclude errors generated by accessing magic properties on `SettingsContainerInterface` can be found in `rules-magic-access.neon`. |
| 52 |
|
| 53 |
|
| 54 |
### Simple usage |
| 55 |
```php |
| 56 |
class MyContainer extends SettingsContainerAbstract{ |
| 57 |
protected string $foo; |
| 58 |
protected string $bar; |
| 59 |
} |
| 60 |
``` |
| 61 |
|
| 62 |
```php |
| 63 |
// use it just like a \stdClass (except the properties are fixed) |
| 64 |
$container = new MyContainer; |
| 65 |
$container->foo = 'what'; |
| 66 |
$container->bar = 'foo'; |
| 67 |
|
| 68 |
// which is equivalent to |
| 69 |
$container = new MyContainer(['bar' => 'foo', 'foo' => 'what']); |
| 70 |
// ...or try |
| 71 |
$container->fromJSON('{"foo": "what", "bar": "foo"}'); |
| 72 |
|
| 73 |
|
| 74 |
// fetch all properties as array |
| 75 |
$container->toArray(); // -> ['foo' => 'what', 'bar' => 'foo'] |
| 76 |
// or JSON |
| 77 |
$container->toJSON(); // -> {"foo": "what", "bar": "foo"} |
| 78 |
// JSON via JsonSerializable |
| 79 |
$json = json_encode($container); // -> {"foo": "what", "bar": "foo"} |
| 80 |
``` |
| 81 |
|
| 82 |
By default, non-existing properties will be ignored and return `null`: |
| 83 |
|
| 84 |
```php |
| 85 |
$container->nope = 'what'; |
| 86 |
|
| 87 |
var_dump($container->nope); // -> null |
| 88 |
``` |
| 89 |
|
| 90 |
You can change this behaviour by adding the attribute `ThrowOnInvalidProperty` to your container class: |
| 91 |
|
| 92 |
```php |
| 93 |
#[ThrowOnInvalidProperty(true)] |
| 94 |
class MyContainer extends SettingsContainerAbstract{ |
| 95 |
// ... |
| 96 |
} |
| 97 |
|
| 98 |
$container->nope = 'what'; // -> throws: attempt to write invalid property: "$nope" |
| 99 |
``` |
| 100 |
|
| 101 |
|
| 102 |
### Advanced usage |
| 103 |
|
| 104 |
Suppose the following trait from library 1: |
| 105 |
|
| 106 |
```php |
| 107 |
trait SomeOptions{ |
| 108 |
protected string $foo; |
| 109 |
protected string $what; |
| 110 |
|
| 111 |
// this method will be called in SettingsContainerAbstract::construct() |
| 112 |
// after the properties have been set |
| 113 |
protected function SomeOptions():void{ |
| 114 |
// just some constructor stuff... |
| 115 |
$this->foo = strtoupper($this->foo); |
| 116 |
} |
| 117 |
|
| 118 |
/* |
| 119 |
* special prefixed magic setters & getters ("set_"/"get_" + property name) |
| 120 |
*/ |
| 121 |
|
| 122 |
// this method will be called from __set() when property $what is set |
| 123 |
protected function set_what(string $value):void{ |
| 124 |
$this->what = md5($value); |
| 125 |
} |
| 126 |
|
| 127 |
// this method is called on __get() for the property $what |
| 128 |
protected function get_what():string{ |
| 129 |
return 'hash: '.$this->what; |
| 130 |
} |
| 131 |
} |
| 132 |
``` |
| 133 |
|
| 134 |
And another trait from library 2: |
| 135 |
|
| 136 |
```php |
| 137 |
trait MoreOptions{ |
| 138 |
protected string $bar = 'whatever'; // provide default values |
| 139 |
} |
| 140 |
``` |
| 141 |
|
| 142 |
We can now plug the several library options together to a single class/object: |
| 143 |
|
| 144 |
```php |
| 145 |
$commonOptions = [ |
| 146 |
// SomeOptions |
| 147 |
'foo' => 'whatever', |
| 148 |
// MoreOptions |
| 149 |
'bar' => 'nothing', |
| 150 |
]; |
| 151 |
|
| 152 |
$container = new class ($commonOptions) extends SettingsContainerAbstract{ |
| 153 |
use SomeOptions, MoreOptions; |
| 154 |
}; |
| 155 |
|
| 156 |
var_dump($container->foo); // -> WHATEVER (constructor ran strtoupper on the value) |
| 157 |
var_dump($container->bar); // -> nothing |
| 158 |
|
| 159 |
$container->what = 'some value'; |
| 160 |
var_dump($container->what); // -> hash: 5946210c9e93ae37891dfe96c3e39614 (custom getter added "hash: ") |
| 161 |
``` |
| 162 |
|
| 163 |
### A note on property hooks (PHP 8.4+) |
| 164 |
|
| 165 |
Property hooks are called whenever a property is accessed (except from within the hook itself of course), which means that the custom get/set methods this library allows would conflict when a custom method is defined for a property that also has a hook defined. |
| 166 |
To prevent double method calls, the internal methods `hasSetHook()` and `hasGetHook()` have been introduced, and are called whenever the magic get/set methods are called: when both, a custom method and a property hook exist, only the property hook will be called. |
| 167 |
<br/>Public properties will never call the magic get/set, however, their hooks *will* be called. (un)serializing a `SettingsContainerInterface` instance will bypass magic get/set and existing property hooks, while JSON de/encode as will call magic get/set or existing hooks explicitly via the `toArray()` and `fromIterable()` methods. |
| 168 |
|
| 169 |
```php |
| 170 |
class PropertyHooksContainer extends SettingsContainerAbstract{ |
| 171 |
|
| 172 |
protected string $someValue{ |
| 173 |
set => doStuff($value); |
| 174 |
} |
| 175 |
|
| 176 |
// this method will be ignored in magic calls as a "set" hook on the property exists |
| 177 |
protected function set_someValue(string $value):void{ |
| 178 |
$this->someValue = doOtherStuff($value); |
| 179 |
} |
| 180 |
|
| 181 |
// this custom method will be called as the property has no "get" hook |
| 182 |
protected function get_someValue():string{ |
| 183 |
return doWhatever($this->someValue); |
| 184 |
} |
| 185 |
|
| 186 |
// this property will never trigger the magic get/set and associated methods |
| 187 |
public string $otherValue{ |
| 188 |
set => doStuff($value); |
| 189 |
get => $this->otherValue; |
| 190 |
} |
| 191 |
|
| 192 |
} |
| 193 |
``` |
| 194 |
|
| 195 |
|
| 196 |
### API |
| 197 |
|
| 198 |
#### [`SettingsContainerAbstract`](https://github.com/chillerlan/php-settings-container/blob/main/src/SettingsContainerAbstract.php) |
| 199 |
|
| 200 |
| method | return | info | |
| 201 |
|--------------------------------------------|------------------------------|---------------------------------------------------------------------------------------------------------------------| |
| 202 |
| `__construct(iterable $properties = null)` | - | calls `construct()` internally after the properties have been set | |
| 203 |
| `__get(string $property)` | mixed | calls `$this->{'get_'.$property}()` if such a method exists | |
| 204 |
| `__set(string $property, $value)` | void | calls `$this->{'set_'.$property}($value)` if such a method exists | |
| 205 |
| `__isset(string $property)` | bool | | |
| 206 |
| `__unset(string $property)` | void | | |
| 207 |
| `__toString()` | string | a JSON string | |
| 208 |
| `toArray()` | array | | |
| 209 |
| `fromIterable(iterable $properties)` | `SettingsContainerInterface` | | |
| 210 |
| `toJSON(int $jsonOptions = null)` | string | accepts [JSON options constants](http://php.net/manual/json.constants.php) | |
| 211 |
| `fromJSON(string $json)` | `SettingsContainerInterface` | | |
| 212 |
| `jsonSerialize()` | mixed | implements the [`JsonSerializable`](https://www.php.net/manual/en/jsonserializable.jsonserialize.php) interface | |
| 213 |
| `serialize()` | string | implements the [`Serializable`](https://www.php.net/manual/en/serializable.serialize.php) interface | |
| 214 |
| `unserialize(string $data)` | void | implements the [`Serializable`](https://www.php.net/manual/en/serializable.unserialize.php) interface | |
| 215 |
| `__serialize()` | array | implements the [`Serializable`](https://www.php.net/manual/en/language.oop5.magic.php#object.serialize) interface | |
| 216 |
| `__unserialize(array $data)` | void | implements the [`Serializable`](https://www.php.net/manual/en/language.oop5.magic.php#object.unserialize) interface | |
| 217 |
|
| 218 |
|
| 219 |
#### Internal (protected) methods |
| 220 |
|
| 221 |
| method | return | info | |
| 222 |
|--------------------------------------|--------|-------------------------------------------------------------------------------| |
| 223 |
| `construct()` | void | calls a method with trait name as replacement constructor for each used trait | |
| 224 |
| `isPrivate(string $property)` | bool | private properties are excluded from magic calls | |
| 225 |
| `hasSetHook(string $property)` | bool | | |
| 226 |
| `hasGetHook(string $property)` | bool | | |
| 227 |
|
| 228 |
|
| 229 |
## Disclaimer |
| 230 |
This might be either an absolutely brilliant or completely stupid idea - you decide (in hindsight it was a great idea I guess - property hooks made their way into PHP 8.4). |
| 231 |
<br/>Also, this is not a dependency injection container. Stop using DI containers FFS. |