markhuot / craft-data
1.0.0
2022-10-25 12:40 UTC
Requires
- craftcms/cms: ^4.2
- hashids/hashids: ^4.1
- markhuot/data: ^1.0
Requires (Dev)
- markhuot/craft-pest: @dev
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); } }