mpyw/sharable-value-objects

共享包含相同原始值的单例值对象。

v1.0.3 2024-01-22 06:52 UTC

This package is auto-updated.

Last update: 2024-09-22 08:24:17 UTC


README

Build Status Coverage Status

共享包含相同原始值的单例值对象。

重要

单例对象保持在WeakReference下。

技巧

您可以通过===运算符比较对象,就像原始值一样!

Value::create('one') === Value::create('one')  // This should be true
Value::create('one') === Value::create('two')  // This should be false

安装

composer require mpyw/sharable-value-objects

注意

PHP 8.3.2由于PHP核心中的错误而不兼容。

使用方法

class ScreenName
{
    // 1. Mixin Sharable trait family
    use SharableString;

    // 2. Write your instantiation logic here
    public static function create(string $value): static
    {
        // Validation/Assertion
        if (!preg_match('/\A@\w{4,15}\z/', $value)) {
            throw new \InvalidArgumentException("invalid screen_name: $value");
        }

        // ** Call static::acquire() to get instance **
        return static::acquire($value);
    }

    // 3. Write your raw presentation logic here
    public function value(): string
    {
        // ** Call $this->getOriginalValue() to retrieve original value **
        return $this->getOriginalValue();
    }
}
class ScreenNameTest extends TestCase
{
    public function testSame(): void
    {
        // Same parameters yield the same instance
        $this->assertSame(
            ScreenName::create('@mpyw'),
            ScreenName::create('@mpyw'),
        );
    }

    public function testDifferent(): void
    {
        // Different parameters yield different instances
        $this->assertNotSame(
            ScreenName::create('@mpyw'),
            ScreenName::create('@X'),
        );
    }
}