PHP code example of phpgears / dto

1. Go to this page and download the library: Download phpgears/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/ */

    

phpgears / dto example snippets




use Gears\Immutability\ImmutabilityBehaviour;
use Gears\DTO\DTO;
use Gears\DTO\PayloadBehaviour;

class MyDTO implements DTO, MyDTOInterface
{
    use ImmutabilityBehaviour, PayloadBehaviour {
        PayloadBehaviour::__call insteadof ImmutabilityBehaviour;
    }

    public function __construct(array $parameters)
    {
        $this->assertImmutable();

        $this->setPayload($parameters);
    }

    final public function getAllowedInterfaces(): array
    {
        return [DTO::class, MyDTOInterface::class];
    }
}

use Gears\DTO\AbstractScalarDTO;

/**
 * @method hasName(): bool
 * @method getName(): string
 * @method hasLastName(): bool
 * @method getLastName(): string
 * @method hasDate(): bool
 * @method getDate(): \DateTimeImmutable
 */
class MyDTO extends AbstractScalarDTO
{
    /**
     * Custom named constructor.
     *
     * @param string $name
     * @param string $lastName
     * @param DateTimeImmutable $date
     * 
     * @return self
     */
    public static function instantiate(
        string $name,
        string $lastName,
        \DateTimeImmutable $date
    ): self {
        return new static([
            'name' => $name,
            'lastName' => $lastName,
            'date' => $date->setTimezone(new \DateTimeZone('UTC'))->format('U'),
        ]);
    }

    /**
     * Transforms 'date' parameter every time it is accessed.
     */
    protected function outputDate(string $date): \DateTimeImmutable
    {
        return DateTimeImmutable::createFromFormat('U', $date);
    }
}