Flexible DTO Documentation

Accessing Object Properties

Once you have created a DTO, there are a multitude of ways to access object properties in PHP. They can be accessed individually, or as a group.

$userDTO = new UserDTO([
    'first_name' => 'John',
]);

Accessing individual properties

Properties can be accessed using the object's property syntax. Additionally, properties can be accessed using the magic get methods without having to define them on the DTO.

$userDTO->first_name; // John
$userDTO->firstName; // John
$userDTO->firstName(); // John
$userDTO->getFirstName(); // John

Using the get Method

Properties can also be accessed using the get method. This is useful when you want to provide a default value if the property does not exist.

$userDTO->get('first_name', 'Default'); // John

Accessing multiple properties

There are a handful of ways to access groups of properties on a DTO.

class UserDTO extends DataTransferObject
{
    protected bool $ignoreNonPermittedProperties = false;

    protected function allowedProperties(): array
    {
        return [
            'first_name',
            'last_name',
            'company_name',
            'website',
        ];
    }
}

$userDTO = new UserDTO([
    'first_name' => 'John',
    'last_name' => 'Doe',
    'company_name' => 'Tighten',
]);

Get All Properties

You can get all properties on a DTO using the getAll method. This will return an array of all properties on the DTO. If a property is not set, it will return null.

$userDTO->getAll(); 
//[
//  "first_name" => "John",
//  "last_name" => "Doe",
//  "company_name" => "Tighten",
//  "website" => null,
//]

Get only Populated Properties

You can get only the populated properties on a DTO using the getPopulated method. This will ignore any properties that have not been set during object creation.

$userDTO->getPoplulated();
//[
//  "first_name" => "John",
//  "last_name" => "Doe",
//  "company_name" => "Tighten",
//]