Skip to content

Basic Example

Matthew Jordan edited this page Apr 23, 2022 · 1 revision

Example

Here is a basic example on how one could implement this library:

class User {
	use MarshalTrait;
	
	public function __construct(
        #[Field(name: "first-name")]
        public string $firstName,
        #[Field(name: "last-name")]
        public string $lastName,
        #[Field]
        public int $age,
        #[Field]
        public string $email
	) {}
}

// NOTE: This uses promoted properties to make it easier to construct.
// You can learn more about this below.

// Marshalling
$user = new User(firstName: "John", lastName: "Doe", age: 30, email: "johndoe@gmail.com");
$data = $user->marshal(); // ["first-name" => "John", "last-name" => "Doe", "age" => 30, "email" => "johndoe@gmail.com"]

$data["first-name"] = "Jane"; // Changing the first name
$data["email"] = "janedoe@gmail.com"; // Changing the email

// Unmarshalling
$user = User::unmarshal($data); // User(firstName: "Jane", lastName: "Doe", age: 30, email: "janedoe@gmail.com")

Clone this wiki locally