markhuot/craft-data

安装: 2

依赖项: 0

建议者: 0

安全性: 0

星标: 0

关注者: 2

分支: 0

开放性问题: 0

类型:craft-plugin

1.0.0 2022-10-25 12:40 UTC

This package is auto-updated.

Last update: 2024-08-25 16:34:31 UTC


README

自动将POST数据转换为强类型数据对象。只需在控制器方法中附加一个属性即可完成转换。

class EntryController extends Controller
{
    #[BodyParams(EntryUpdateParams::class)]
    function actionUpdate()
    {
        // Now $this->getData() will return an `EntryUpdateParams` with all the
        // data copied over from the POST in to the class
    }
}

数据对象使用公共属性和PHP类型提示来映射所有内容。有关映射的更多详细信息,请参阅markhuot/data

class EntryUpdateParams
{
    public int $elementId;
    public ?string $title;
    public ?string $slug;

    function getElement()
    {
        return \Craft::$app->elements->getElementById($this->elementId);
    }
}

markhuot/data中的所有验证规则都同样适用,因此您可以确保特定字段符合您预期的验证规则。

use Symfony\Component\Validator\Constraints as Assert;

class EntryUpdateParams
{
    #[Assert\NotNull]
    public int $elementId;

    #[Assert\NotEmpty]
    public string $title;

    #[Assert\Regex('/[a-z]0-9_-/i')]
    public ?string $slug;

    function getElement()
    {
        return \Craft::$app->elements->getElementById($this->elementId);
    }
}