PHP code example of anfischer / dto

1. Go to this page and download the library: Download anfischer/dto library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

anfischer / dto example snippets

 php
use Anfischer\Dto\Dto;

class TypeHintedDataTransferObject extends Dto
{
    protected $stringProperty;
    protected $integerProperty;
    
    public function getPropertyType($property): string
    {
        switch ($property) {
            case 'stringProperty':
                return 'string';
            case 'integerProperty':
                return 'integer';
        }
    }
}

$dto = new TypeHintedDataTransferObject;

$dto->stringProperty = 'foo';
$dto->integerProperty = 1;

// ERROR - throws InvalidTypeException since type has to be initialized as string
$dto->stringProperty = 1;

// ERROR - throws InvalidTypeException since type has to be initialized as integer
$dto->integerProperty = 'foo';
 php
use Anfischer\Dto\Dto;

class TypeHintedDataTransferObject extends Dto
{
    protected $mixedProperty;
    
    public function getPropertyType($property): string
    {
        switch ($property) {
            case 'mixedProperty':
                return 'string|integer|array';
        }
    }
}

$dto = new MixedTypeHintedDataTransferObject;

$dto->mixedProperty = 'foo';
$dto->mixedProperty = 1;
$dto->mixedProperty = ['foo', 'bar', 'baz'];

// ERROR - throws InvalidTypeException since type has to be either string, integer or array
$dto->mixedProperty = 1.1;

// ERROR - throws InvalidTypeException since type has to be either string, integer or array
$dto->mixedProperty = false;