zero-to-prod/dynamic-setter

使用动态方法流畅地设置类属性。

v71.0.0 2024-09-05 03:09 UTC

This package is auto-updated.

Last update: 2024-09-05 03:12:01 UTC


README

Repo Latest Version on Packagist test Downloads

使用动态方法流畅地设置类属性。

安装

要安装此软件包,请运行 composer install

composer require zerotoprod/dynamic-setter

用法

DynamicSetter 特性允许您通过方法链轻松创建类实例并动态设置属性。它通过 set_* 方法提供了一种简单的方式来管理对象实例化和属性设置。

要使用 DynamicSetter 特性,将其包含到您的类中,并定义您想要动态设置的属性。

use Zerotoprod\StreamContext\DynamicSetter;

class User
{
    use DynamicSetter;

    public $name;
    public $email;
}

$user = User::new()
    ->set_name('John Doe')
    ->set_email('john.doe@example.com');

echo $user->name;  // Output: John Doe
echo $user->email; // Output: john.doe@example.com

嵌套对象

您还可以在包含其他对象的类中使用 DynamicSetter 特性,允许您在嵌套结构中设置属性。

class Address
{
    use DynamicSetter;

    public $city;
    public $postalCode;
}

class Customer
{
    use DynamicSetter;

    public $name;
    public $address;
}

$customer = Customer::new()
    ->set_name('Jane Doe')
    ->set_address(
        Address::new()
            ->set_city('New York')
            ->set_postalCode('10001')
    );

echo $customer->name;                   // Output: Jane Doe
echo $customer->address->city;          // Output: New York
echo $customer->address->postalCode;    // Output: 10001