lexide/clay

创建轻量级模型并将复杂数据结构应用于它们

3.1.1 2024-06-06 14:11 UTC

README

Clay 允许您使用从数据库或其他数据存储中获取的数据数组填充模型对象,而无需手动应用值。数据根据每个属性的名称应用到模型上,可以直接应用,也可以通过可用的话通过设置器应用。Clay 支持嵌套数组数据和包含其他对象(在多层数据结构中)的属性,并在将数据应用于模型时自动将键转换为驼峰式。

安装

通过 composer 安装

composer require lexide/clay

简单示例

要使用 Clay,模型应该使用 ModelTrait 特性和实现一个调用 loadData() 方法的函数

class Model
{
    use Lexide\Clay\Model\ModelTrait;

    public $property;
    ...

    public function __construct(array $data = [])
    {
        $this->loadData($data);
    }

}

然后可以实例化模型,将数据传递给构造函数

$data = ["property" => "value", ...];
$model = new Model($data);

echo $model->property; // outputs "value"

带有下划线或空格键的数据将应用于它们的驼峰式对应项

$data = [
    "long_field_name" => ... // will apply to the property "longFieldName"
    "property name with spaces" => ... // will apply to "propertyNameWithspaces"
];

对象实例化

如果您想在第二个类中包含数据子集,只需在设置器中为提供的参数添加类型提示即可

class Address
{
    use Lexide\Clay\Model\ModelTrait;

    public $street;
    public $city;

    public function __construct(array $data = [])
    {
        $this->loadData($data);
    }
}

class Customer
{
    use Lexide\Clay\Model\ModelTrait;

    protected $address;

    public function __construct(array $data = [])
    {
        $this->loadData($data);
    }

    public function setAddress(Address $address)
    {
        $this->address = $address;
    }

}

$data = [
    "address": [
        "street" => "1 test street",
        "city" => "exampleton"
    ]
]

$customer = new Customer($data);
echo $customer->getAddress()->city; // outputs "exampleton"

对象集合

对于数组或对象集合也可以这样做。Clay 会寻找该属性的 "add" 方法以确定要实例化的类

class Customer
{
    use Lexide\Clay\Model\ModelTrait;

    protected $addresses = [];

    public function __construct(array $data = [])
    {
        $this->loadData($data);
    }

    public function setAddresses(array $addresses)
    {
        $this->addresses = [];
        foreach ($addresses as $address) {
            $this->addAddresses($address));
        }
    }

    public function addAddresses(Address $address)
    {
        $this->addresses[] = $address;
    }

}

$data = [
    "addresses": [
        [
            "street" => "1 Test street",
            "city" => "Exampleton"
        ],
        [
            "street" => "22 Sample row",
            "city" => "Testville"
        ]
    ]
]

$customer = new Customer($data);