github编辑

Attribute Grouping

Property grouping provides a flexible way to control the input and output behavior of properties, allowing fine-grained management of data conversion in different scenarios.


Explanation of Grouping Principle

  • Use the #[Groups(...)] annotation to assign a property to one or more groups.

  • Supports:

    • For input: Filter data fields by group

    • For output: Select output fields by group

  • Properties without a specified group will automatically be assigned to the "default" group.


Basic Example

use Astral\Serialize\Attributes\Groups;
use Astral\Serialize\Serialize;

class User extends Serialize {

    #[Groups('update', 'detail')]
    public string $id;

    #[Groups('create', 'update', 'detail')]
    public string $name;

    #[Groups('create', 'detail')]
    public string $username;

    #[Groups('other')]
    public string $sensitiveData;

    // Not assigned to a group, defaults to the 'default' group
    public string $noGroupInfo;

    public function __construct(
        #[Groups('create', 'detail')]
        public readonly string $email,

        #[Groups('update', 'detail')]
        public readonly int $score
    ) {}
}

Receive by Group

Output by Group

Grouping of Nested Objects

最后更新于