Skip to content

Share value objects that contain the same primitive value as a singleton

License

Notifications You must be signed in to change notification settings

mpyw/sharable-value-objects

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

sharable-value-objects

Build Status Coverage Status

Share value objects that contain the same primitive value as a singleton.

Important

Singleton objects are kept under WeakReference.

Tip

You can compare objects like primitives through === operator!

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

Installing

composer require mpyw/sharable-value-objects

Caution

PHP 8.3.2 is incompatible due to the bug in the PHP core.

Usage

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'),
        );
    }
}

About

Share value objects that contain the same primitive value as a singleton

Resources

License

Stars

Watchers

Forks

Languages