immutablephp/immutable
Composer 安装命令:
composer require immutablephp/immutable
包简介
Immutable base objects, value objects, and value bag.
README 文档
README
Provides truly immutable value objects and an immutable value bag, along with base Immutable and ValueObject classes for your own objects. It helps to prevent against the oversights described by the article Avoiding Quasi-Immutable Objects in PHP.
Overview
The base Immutable class protects against common oversights in PHP regarding immutables:
-
It defines
final public function __set()andfinal public function __unset()to prevent adding and mutating undefined properties. -
It defines
final public function offsetSet()andfinal public function offsetUnset()to prevent adding and mutating values via ArrayAccess. -
It prevents multiple calls to
__construct()to re-initialize the object properties.
Further, the base ValueObject class with() method checks the types of all
incoming values to make sure they are themselves immutable. It does so via the
static methods on the Type class.
The Type class recognizes scalars and nulls as immutable. All other non-object values (such are resources and arrays) are rejected as mutable.
When it comes to objects, the Type class recognizes anything descended from
Immutable as immutable, as well as DateTimeImmutable. To allow Type to
recognize other immutable classes, call Type::register() with a variadic list
of fully-qualified class names that you want to treat as immutable.
Making Your Own Immutable Value Objects
Note:
This package can only do so much to keep you from accidentally overlooking mutability. For example, The Immutable and ValueObject classes cannot prevent you from deliberately adding your own mutable behaviors. Likewise, it is not possible to prevent against using reflection to mutate an object from the outside.
To create your own immutable value object, extend ValueObject with your own properties.
use Immutable\ValueObject\ValueObject; class Address extends ValueObject { protected $street; protected $city; protected $region; protected $postcode; }
Then add a with*() method to allow changing of those values on a clone of the
object, using the protected with() method on the base ValueObject.
class Address extends ValueObject { protected $street; protected $city; protected $region; protected $postcode; public function withChanged( string $street, string $city, string $region, string $postcode ) { return $this->with([ 'street' => $street, 'city' => $city, 'region' => $region, 'postcode' => $postcode ]); } }
Finally, use that method in the constructor to initialize the properties, and
call parent::__construct() to finish initialization.
class Address extends ValueObject { protected $street; protected $city; protected $region; protected $postcode; public function __construct( string $street, string $city, string $region, string $postcode ) { $this->withChanged($street, $city, $region, $postcode); parent::__construct(); } public function withChanged( string $street, string $city, string $region, string $postcode ) : self { return $this->with([ 'street' => $street, 'city' => $city, 'region' => $region, 'postcode' => $postcode ]); } }
Warning:
If you do not call
parent::__construct()then the Value Object will not know that it has been initialized, and it will be possible to call the constructor multiple time to re-initialize the object.
Now you have an immutable Value Object.
You may find it useful to add validation; do so in your with*() methods,
either directly or by calling a validation mechanism.
public function withChanged( string $street, string $city, string $region, string $postcode ) { $valid = AddressValidator::validate($street, $city, $region, $postcode); if (! $valid) { throw new \RuntimeException('address is not valid'); } return $this->with([ 'street' => $street, 'city' => $city, 'region' => $region, 'postcode' => $postcode ]); }
Provided Immutable Value Objects
This package provides several Value Objects, both as examples and for common usage.
CreditCard
use Immutable\ValueObject\CreditCard; $creditCard = new CreditCard('5555-5555-5555-4444'); // reading $creditCard->getNumber(); // '5555555555554444' $creditCard->getBrand(); // 'VISA' // changing $newCreditCard = $creditCard->withNumber('4111-1111-1111-1111'); $newCreditCard->getNumber(); // '4111111111111111' $newCreditCard->getBrand(); // 'MASTERCARD'
use Immutable\ValueObject\Email; $email = new Email('bolivar@example.com'); // reading $email->get(); // 'bolivar@example.com' // changing $newEmail = $email->withAddress('boshag@example.net'); $newEmail->get(); // 'boshag@example.net'
Ip
use Immutable\ValueObject\Ip; $ip = new Ip('127.0.0.1'); // reading $ip->get(); // '127.0.0.1' // changing $newIp = $ip->withAddress('192.168.0.1'); $newIp->get(); // '192.168.0.1'
Isbn
use Immutable\ValueObject\Isbn; $isbn = new Isbn('960-425-059-0'); // reading $isbn->get(); // '960-425-059-0' // changing $newIsbn = $ip->withAddress('0-8044-2957-X'); $newIsbn->get(); // '0-8044-2957-X'
Uri\HttpUri
use Immutable\ValueObject\Uri\HttpUri; $httpUri = new HttpUri( 'http://boshag:bopass@example.com:8080/foo?bar=baz#dib' ); // reading $httpUri->getScheme(); // 'http' $httpUri->getHost(); // 'example.com' $httpUri->getPort(); // 8080 $httpUri->getUser(); // 'boshag' $httpUri->getPass(); // 'bopass' $httpUri->getPath(); // /'foo' $httpUri->getQuery(); // 'bar=baz' $httpUri->getFragment(); // 'dib' // changing $newHttpUri = $httpUri ->withScheme('https') ->withHost('example.net') ->withPort('8888') ->withUser('newuser') ->withPass('newpass') ->withPath('/foo2') ->withQuery('zim=gir') ->withFragment('irk'); $newHttpUri->get(); // 'https://newuser:newpass@example.net:8888/foo2/?zim=gir#irk'
Uuid
use Immutable\ValueObject\Uuid; $uuid = new Uuid('12345678-90ab-cdef-1234-567890123456'); // reading $uuid->get(); // '12345678-90ab-cdef-1234-567890123456' // changing $newUuid = $uuid->withIdentifier('11111111-1111-1111-1111-111111111111'); $newUuid->get(); // '11111111-1111-1111-1111-111111111111' // create a new random UUIDv4 identifier $uuidv4 = Uuid::newVersion4();
Immutable Bag
The Bag is for an arbitrary collection of immutable values, and can be useful for immutable representations of JSON data.
use Immutable\Bag; $bag = new Bag(['foo' => 'bar']); echo $bag->foo; // bar echo $bag['foo']; // bar $bag->foo = 'baz'; // ImmutableObjectException $bag = $bag->with('foo', 'baz'); echo $bag->foo; // baz echo $bag['foo']; // baz unset($bag->foo); // ImmutableObjectException $bag = $bag->without('foo'); $bag->dib; // Notice: $dib not defined $bag = $bag->with('dib', ['zim', 'gir']); foreach ($bag->dib as $key => $value) { echo "$key:$value,"; // 0:zim,1:gir, }
immutablephp/immutable 适用场景与选型建议
immutablephp/immutable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 21.43k 次下载、GitHub Stars 达 79, 最近一次更新时间为 2019 年 01 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 immutablephp/immutable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 immutablephp/immutable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 21.43k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 80
- 点击次数: 1
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2019-01-09