spekkionu/property-access

自动调用属性访问的获取器和设置器的特性。

0.4.0 2015-04-02 02:09 UTC

This package is auto-updated.

Last update: 2024-09-12 13:47:35 UTC


README

Build Status Code Coverage Scrutinizer Code Quality SensioLabsInsight

自动调用属性访问的获取器和设置器的特性。

use Spekkionu\PropertyAccess\PropertyAccessTrait;

class ExampleClass
{
    use PropertyAccessTrait;

    private $name;

    private $email;

}
$example = new ExampleClass();

$example->name = 'Bob';
$example->email = 'bob@example.com';

echo $example->name; // Bob

$example->fill(array(
    'name' => 'Steve',
    'email' => 'steve@example.com'
));

echo $example->email; // steve@example.com

将调用获取器和设置器

您甚至可以使用值对象

use Spekkionu\PropertyAccess\PropertyAccessTrait;

class ExampleClass
{
    use PropertyAccessTrait;

    private $name;

    private $email;

    public function setEmail(EmailAddress $email){
        $this->email = $email;
    }

}

// Value Object
class EmailAddress
{
    private $email;

    public function __construct($email)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException('Not a valid email address.');
        }
        $this->email = $email;
    }

    public function getValue()
    {
        return $this->email;
    }

    public function __toString()
    {
        return $this->getValue();
    }
}

// Usage
$example = new ExampleClass();
$example->email = new EmailAddress('bob@example.com');