AthenaeumAthenaeum
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
  • Version 6.x

    • Release Notes
    • Upgrade Guide
    • New to this...
    • Contribution Guide
    • Security Policy
    • Code of Conduct
    • Origin
  • ACL

    • Introduction
    • How to install
    • Setup
    • Permissions
    • Roles
    • Users
    • Cached Permissions
  • Audit

    • Audit
    • How to install
    • Setup
    • Recording
    • Events
  • Circuits

    • Circuits
    • How to install
    • Setup
    • Usage
    • Events
  • Collections

    • Collections
    • How to install
    • Summation

      • Summation Collection
      • Items Processor
  • Config

    • Configuration Loader
    • How to install
    • Setup
    • Load Configuration Files
    • Custom File Parsers
  • Console

    • Command and Schedule Registration
    • How to install
    • Setup
    • Commands
    • Schedules
  • Container

    • IoC Service Container
    • How to install
    • Container
    • List Resolver
  • Core

    • Athenaeum Core Application
    • How to install
    • Setup
    • Usage

      • Configuration
      • Service Providers
      • Service Container
      • Events
      • Caching
      • Logging
      • Console
      • Task Scheduling
      • Exception Handling
      • Extending Core Application
      • Testing
  • Database

    • Introduction
    • How to install
    • Models

      • Instantiatable
      • Sluggable
    • Query

      • Criteria (Query Filter)
  • Dto

    • Data Transfer Object (DTO)
    • How to install
    • Create Interface
    • Implement DTO
    • How to use
    • Populate
    • Export
    • Json
    • Serialization
    • Nested DTOs
    • Array DTO
  • ETags

    • ETags
    • How to install
    • Setup
    • Usage
    • Generators

      • Default Generator
      • Custom Generator
    • Eloquent Models
    • Macros
  • Events

    • Register Listeners and Subscribers
    • How to install
    • Setup
    • Listeners
    • Subscribers
  • Filters

    • Search Filter Utilities
    • Prerequisites
    • How to install
    • Setup
    • Processor
    • Filters Builder
    • Predefined Resources

      • Search Processor
      • Sorting Processor
      • Constraints Processor
      • Matching Processor
    • Tip: Create a base builder
  • Flysystem

    • Introduction
    • Database Adapter

      • Introduction
      • How to install
      • Setup
      • Data Deduplication
      • MIME-Type Detection
  • Http

    • Api

      • Http API
      • How to install
      • Setup
      • Resources

        • Introduction
        • Timestamps
        • Self-Link
        • Relations
        • Registrar
      • Middleware

        • Introduction
        • Request Must Be Json
        • Capture Fields To Select
    • Clients

      • Http Clients
      • How to install
      • Setup
      • Basic Usage
      • Available Methods

        • Fluent Api
        • Protocol Version
        • Base Uri
        • Http Method and Uri
        • Headers
        • Accept & Content-Type
        • Authentication
        • Http Query
        • Payload Format
        • Payload
        • Attachments
        • Cookies
        • Response Expectations
        • Middleware
        • Conditions
        • Criteria
        • Redirects
        • Timeout
        • Debugging
        • Logging
        • Driver Options
        • Driver
      • Http Query Builder

        • Introduction
        • Select
        • Where
        • Dates
        • Include
        • Pagination
        • Sorting
        • Raw Expressions
        • Custom Grammar
    • Cookies

      • Http Cookies
      • How to install
      • Usage
    • Messages

      • Http Messages
      • How to install
      • Serializers
  • Maintenance

    • Modes

      • Maintenance Modes
      • How to install
      • Setup
      • Basic Usage
      • Available Drivers
  • Mime Types

    • MIME-Types
    • How to install
    • Setup
    • Usage
    • Drivers

      • Available Drivers
      • File Info
  • Properties

    • Properties Overload
    • How to install
    • Usage
    • Naming Convention
    • Properties Visibility
  • Redmine

    • Redmine Api Client
    • How to install
    • Setup
    • General Usage

      • Supported Operations
      • Fetch list of resources
      • Find
      • Fetch
      • Create new record
      • Update existing record
      • Delete existing record
      • Relations
    • Available Resources

      • Predefined Resources
      • Attachments
      • Enumerations
      • Issue Relations
      • Users
      • User Groups
      • Roles
      • Project Memberships
      • Versions (Milestones)
      • Issue Categories
      • Trackers
  • Service

    • Service Registrar
    • How to install
    • How to use
  • Streams

    • Streams
    • How to install
    • Setup
    • How to use

      • Introduction
      • Open and Close
      • Raw Resource
      • Seeking
      • Reading
      • Writing
      • Size
      • Truncate
      • Flush
      • Hash
      • MIME-Type
      • Output
      • Locking
      • Transactions
      • Meta
      • Misc
  • Support

    • Introduction
    • How to install
    • Laravel Aware-of Helpers

      • How to use
      • Enforce Via Interface
      • Custom Default
      • Pros and Cons
      • Available Helpers
    • Aware-of Properties

      • Generator
      • Available Aware-of Helpers
    • Live Templates
  • Testing

    • Introduction
    • How to install
    • Test Cases
    • Testing Aware-of Helpers
  • Utils

    • Introduction
    • How to install
    • Array
    • Duration
    • Json
    • Math
    • Memory
    • Method Helper
    • Invoker
    • Populatable
    • String
    • Version
  • Validation

    • Introduction
    • How to install
    • Setup
    • Rules

      • Alpha-Dash-Dot
      • Semantic Version
You are viewing documentation for an outdated version. It is no longer supported!

Array DTO

While the Dto abstraction is good for situations where you must adhere to interfaces that define getters and setters, it can be a bit cumbersome to maintain a large number classes. This can especially be true, if you must create DTOs to represent all the resources available for a large scale API.

In such situations, the ArrayDto abstraction is perhaps better suited. As it's name suggests, it uses an array to keep track of it's properties. It functions almost the exact same way, as the Dto abstraction.

Creating an Array-Dto

Extend the ArrayDto abstraction and declare your DTO's properties, via the $allowed variable.

The keys of the $allowed variable correspond to your property's name, whereas the values correspond to the property's data type.

Whenever your DTO is populated, it will automatically ensure to cast the property to it's decalred type.

use Aedart\Dto\ArrayDto;

class Organisation extends ArrayDto
{
    protected array $allowed = [
        'name'          => 'string',
        'employees'     => 'int',
        'hasInsurance'  => 'bool',
        'profitScore'   => 'float',
        'boardMembers'  => 'array',
        'started'       => 'date',
    ];
}

Working with Array-Dto

Once you have created your DTO instance, you can work with it just like the Dto abstraction.

$dto = new Organisation([
    'name'          => 'Acme Ltd',
    'employees'     => 134,
    'hasInsurance'  => true,
    'profitScore'   => 33.8,
    'boardMembers'  => [ 'Sawyer', 'Stine', 'Jim' ],
    'started'       => '2018-06-15 10:00:00'
]);

echo $dto->name; // Acme Ltd

$dto['employees'] = 136; // 'employees' property set to 136

echo $dto->toJson(); // Json representation of dto

Supported Types

By default, each declared property is nullable, meaning that a property is either of the declared data type or null.

The following are the supported data types:

  • string
  • int
  • float,
  • bool
  • array
  • date (property is parsed into a Carbon instance)

Note

You can change how each type is casted or converted, by overwriting the castPropertyValue() method.

Alternatively, you can overwrite each type's individual casting method, e.g. castAsDate(), castAsBoolean(), castAsString(), ...etc.

For more information, please review the source code of \Aedart\Dto\Partials\CastingPartial trait, which is used by the ArrayDto.

Nested DTOs

In order to work with nested DTOs, you must declare their class path in the $allowed property.

Other than that, the populate mechanism works in same way, as previously mentioned.

use Aedart\Dto\ArrayDto;
use Acme\Dto\Address;

class Organisation extends ArrayDto
{
    protected array $allowed = [
        'name'          => 'string',
        'address'       => Address::class,
    ];
}

Union Types

The same union type handling is supported by the ArrayDto abstraction, as for the regular Dto.

class Article extends ArrayDto
{
    protected array $allowed = [
        'id' => 'string|int|float|bool|null',
        'content' => 'array|null',
        'createdAt' => 'date|null',
        'author' => ['string', Person::class, Organisation::class, 'null'],
    ];
}

Review the DTO "Union Types" documentation for details and additional examples.

Getters and Setters

Should you require to mutate a property, then you can do so by defining an accessor or mutator method.

The naming rules, for your property getter or setter method, are the same as for overloading.

use Aedart\Dto\ArrayDto;

class Organisation extends ArrayDto
{
    protected array $allowed = [
        'name'          => 'string', // Type ignored!
    ];
    
    public function setName(?string $name)
    {
        $this->properties['name'] = strtoupper($name);

        return $this;
    }

    public function getName() : ?string
    {
        return $this->properties['name'] ?? null;
    }
}

Warning

When you define accessor or mutator method for a property, it's initial type declaration and casting is ignored. If special casting or converting is required, then you must manually handle such in your methods.

Edit page
Last Updated: 16/02/2023, 09:10
Contributors: Alin Eugen Deac, alin
Prev
Nested DTOs