├── LICENSE ├── README.md ├── composer.json └── src └── Immutable.php /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) Matthias Noback 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is furnished 8 | to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Convenient immutability for (some) PHP objects 2 | 3 | **Warning: I didn't use this library "in the wild" - please let me know if it works in your situation** 4 | 5 | [![Build Status][ico-travis]][link-travis] 6 | [![Coverage Status][ico-coveralls]][link-coveralls] 7 | [![Latest Version on Packagist][ico-version]][link-packagist] 8 | [![Total Downloads][ico-downloads]][link-downloads] 9 | [![Software License][ico-license]](LICENSE.md) 10 | 11 | ## Installation 12 | 13 | Just run: 14 | 15 | composer require matthiasnoback/convenient-immutability 16 | 17 | ## Introduction 18 | 19 | I've often encountered the following situation (in particular when working with [command objects](http://php-and-symfony.matthiasnoback.nl/2015/01/a-wave-of-command-buses/)). 20 | 21 | 1. I start with a simple object (in fact, a DTO), with just some public properties. 22 | 2. The Symfony Form component copies some values into the object's properties. 23 | 3. I copy some extra data into the object (like a generated UUID). 24 | 4. I then use that object as a command or query message, handing it over to some inner layer of my application. 25 | 26 | In other words, I have a class that looks like this: 27 | 28 | ```php 29 | class OrderSeats 30 | { 31 | public $id; 32 | public $userId; 33 | public $seatNumbers = []; 34 | } 35 | ``` 36 | 37 | And use it like this: 38 | 39 | ```php 40 | $form = $this->factory->create(OrderSeatsFormType::class); 41 | $form->submit($request); 42 | $command = $form->getData(); 43 | $command->id = Uuid::uuid4(); 44 | 45 | $commandBus->handle($command); 46 | ``` 47 | 48 | Then **I want it to be impossible to change any field on the (command) object**, making it effectively *immutable*. 49 | 50 | The `ConvenientImmutability\Immutable` trait solves this problem. When your class uses this trait, it: 51 | 52 | - Allows form components and the likes to put anything in your object in any particular order they like. 53 | - Allows you to get the data from it by simply accessing its (public) variables. 54 | - Doesn't allow anyone to overwrite previously set data. 55 | 56 | ## Why would you do this? 57 | 58 | - To feel less insecure about using public properties for your desirably immutable objects. 59 | - To prevent accidental writes to objects you assumed were immutable. 60 | 61 | ## What's the problem with this approach? 62 | 63 | - Your objects may be immutable... 64 | - but they can still exist in an inconsistent state. 65 | 66 | Is this bad? I don't think so. As long as you validate the objects (e.g. using the Symfony Validator) and then throw them into your domain layer, which contains the actual safeguards against inconsistent state. 67 | 68 | (You can also just use public properties and treat them as "set once, never again" in other parts of your application.) 69 | 70 | ## License 71 | 72 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 73 | 74 | [ico-version]: https://img.shields.io/packagist/v/matthiasnoback/convenient-immutability.svg?style=flat-square 75 | [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square 76 | [ico-coveralls]: https://img.shields.io/coveralls/matthiasnoback/convenient-immutability.svg?style=flat-square 77 | [ico-travis]: https://img.shields.io/travis/matthiasnoback/convenient-immutability.svg?style=flat-square 78 | [ico-downloads]: https://img.shields.io/packagist/dt/matthiasnoback/convenient-immutability.svg?style=flat-square 79 | 80 | [link-packagist]: https://packagist.org/packages/matthiasnoback/convenient-immutability 81 | [link-coveralls]: https://coveralls.io/github/matthiasnoback/convenient-immutability 82 | [link-travis]: https://travis-ci.org/matthiasnoback/convenient-immutability 83 | [link-downloads]: https://packagist.org/packages/matthiasnoback/convenient-immutability 84 | [link-author]: https://github.com/matthiasnoback 85 | [link-contributors]: ../../contributors 86 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "matthiasnoback/convenient-immutability", 3 | "description": "Make objects initially inconsistent, yet eventually immutable", 4 | "license": "MIT", 5 | "authors": [ 6 | { 7 | "name": "Matthias Noback", 8 | "email": "matthiasnoback@gmail.com" 9 | } 10 | ], 11 | "require": { 12 | "php": ">=7.2" 13 | }, 14 | "require-dev": { 15 | "ramsey/uuid": "^3.9", 16 | "satooshi/php-coveralls": "^2.2", 17 | "phpunit/phpunit": "^8.5", 18 | "symfony/form": "^4.2" 19 | }, 20 | "autoload": { 21 | "psr-4": { 22 | "ConvenientImmutability\\": "src/" 23 | } 24 | }, 25 | "autoload-dev": { 26 | "psr-4": { 27 | "ConvenientImmutability\\Test\\": "test/" 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Immutable.php: -------------------------------------------------------------------------------- 1 | true, 17 | '_userDefinedValues' => true, 18 | '_userDefinedProperties' => true, 19 | ]; 20 | 21 | public function __construct() 22 | { 23 | // take over all user-defined non-static properties 24 | foreach ((new ReflectionObject($this))->getProperties() as $property) { 25 | $propertyName = $property->getName(); 26 | 27 | if (isset(self::$_doNotTakeOverProperties[$propertyName]) || $property->isStatic()) { 28 | continue; 29 | } 30 | 31 | $this->_userDefinedProperties[$propertyName] = true; 32 | if (PHP_VERSION_ID < 70400 || $property->isInitialized($this)) { 33 | $this->_defaultValues[$propertyName] = $property->getValue($this); 34 | } 35 | unset($this->{$propertyName}); 36 | } 37 | } 38 | 39 | final public function __set($name, $value) 40 | { 41 | if (!isset($this->_userDefinedProperties[$name])) { 42 | throw new LogicException('Unknown property "' . $name . '"'); 43 | } 44 | 45 | if (array_key_exists($name, $this->_userDefinedValues)) { 46 | throw new LogicException('You can not overwrite the value for property "' . $name . '"'); 47 | } 48 | 49 | $this->_userDefinedValues[$name] = $value; 50 | } 51 | 52 | final public function __get($name) 53 | { 54 | if (!isset($this->_userDefinedProperties[$name])) { 55 | throw new LogicException('Unknown property "' . $name . '"'); 56 | } 57 | 58 | if (array_key_exists($name, $this->_userDefinedValues)) { 59 | return $this->_userDefinedValues[$name]; 60 | } 61 | 62 | return $this->_defaultValues[$name]; 63 | } 64 | 65 | final public function __wakeup() 66 | { 67 | foreach ($this->_userDefinedProperties as $property => $defined) { 68 | unset($this->{$property}); 69 | } 70 | } 71 | } 72 | --------------------------------------------------------------------------------