PHP code example of mpyw / sharable-value-objects

1. Go to this page and download the library: Download mpyw/sharable-value-objects library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mpyw / sharable-value-objects example snippets


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

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