Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

Overview

Super Simple DTO

Latest Version on Packagist Tests Total Downloads

Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

This is a laravel package and laravel/framework is part of the package dependencies. Please, make sure you have no problem with that before using.

Why Bother.

The spatie team has already created an awesome package that serves as a great solution for DTO objects. But, for me, it's full of features that I don't use and it seems like an overkill for me when I just wanted simple solution for DTO work.

Installation

You can install the package via composer:

composer require mohammedmanssour/super-simple-dto

Usage

  1. Apply the AsDTO trait to your data object
use MohammedManssour\DTO\Concerns\AsDTO;

class UserData
{
    use AsDTO;

    public string $name;

    public string $email;

    public BalanceData $balance;

    public Status $status;
}
  1. use on of these static methods to convert data into DTP:
    1. fromCollection: converts collections to DTO objects.
    2. fromArray: converts array to DTO objects.
    3. fromModel: converts model to DTO objects. It works with the data available with $model->getAttributes() method.
    4. fromRequest: converts laravel requests to DTO objects. It works with the data available with validated(). In case validated method is not available, it'll use the all() method. You can also force using request's all method by passing true as a second parameter.
UserData::fromCollection(collect([]));

UserData::fromArray([]);

UserData::fromModel($model);

UserData::fromRequest($request);

How DTO is populated:

The AsDTO will assign values to DTO attributes depending of the keys. and attributes that has no key match will not be initialized/assigned

$data = [
    'name' => 'Mohammed Manssour',
    'email' => '[email protected]'
];
$dto = UserData::fromArray();

$this->assertEquals($data['name'], $dto->name);
$this->assertEquals($data['email'], $dto->email);

$this->assertFalse(isset($dto->balance));
$this->assertFalse(isset($dto->status));

Handling special attributes:

In case you have an attribute that needs special care. you can add a method to your dto than have the same name as your attribute and take care of the conversion.

use MohammedManssour\DTO\Concerns\AsDTO;

class BalanceData
{
    use AsDTO;

    public float $bitcoin;

    public int $usdollar;
}

enum Status: string
{
    case Active = 'active';
    case Suspended = 'suspended';
}

class UserData
{
    use AsDTO;

    ....

    public BalanceData $balance;

    public Status $status;

    public function balance($value)
    {
        return $this->balance = BalanceData::fromArray($value);
    }

    public function status($value)
    {
        return $this->status = Status::from($value);
    }
}

$data = [
    'balance' => [
        'bitcoin' => 10,
        'usdollar' => 100
    ],
    'status' => 'active'
];

$dto = UserData::fromArray($data)

$this->assertInstanceOf(BalanceData::class, $dto->balance);
$this->assertEquals($data['balance']['bitcoin'], $dto->balance->bitcoint);
$this->assertEquals($data['balance']['usdollar'], $dto->balance->usdollart);


$this->assertInstanceOf(Status::class, $dto->status);
$this->assertEquals(Status::Active, $dto->status);

converting DTO to array

You can convert dto to array using DTO method

$arr = $dto->toArray()

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

You might also like...
A PHP Library To Make Your Work Work Easier/Faster

This Is A Php Library To Make Your Work Easier/Faster,

A Zabbix module to show groups/hosts as a tree under Monitoring -> Hosts Tree menu item
A Zabbix module to show groups/hosts as a tree under Monitoring - Hosts Tree menu item

zabbix-module-hosts-tree Written according to Zabbix official documentation https://www.zabbix.com/documentation/current/manual/modules A Zabbix modul

Joole Reflector - used to work with the properties of objects, their changes and merges

Joole Reflector allows you to change protected, as well as private properties of an object.

This package provides a simple and intuitive way to work on the Youtube Data API. It provides fluent interface to Youtube features.

Laravel Youtube Client This package provides a simple and intuitive way to work on the Youtube Data API. It provides fluent interface to Youtube featu

A tool for diff'ing this and OpenTHC lab metrics, creating their objects, and docs.

wcia-analytes-tool Consumes OpenTHC Lab Metrics and WCIA Analytes, and produces diff objects and docs for use in WA State interop. version 0.9.8 Getti

PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects.

📢 Yell PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects. Requirement

Get mobile app version and other related data from Google Play Store, Apple App Store and Huawei AppGallery

Mobile App Version Get mobile app version and other related data from Google Play Store, Apple App Store and Huawei AppGallery. Installation Add to co

Melek Berita Backend is a service for crawling data from various websites and processing the data to be used for news data needs.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

HLedger is cross-platform accounting software for both power users and folks new to accounting
HLedger is cross-platform accounting software for both power users and folks new to accounting

HLedger Plain Text Accounting on Nextcloud HLedger is cross-platform accounting software for both power users and folks new to accounting. It's good f

Comments
  • Bump aglipanci/laravel-pint-action from 1.0.0 to 2.3.0

    Bump aglipanci/laravel-pint-action from 1.0.0 to 2.3.0

    Bumps aglipanci/laravel-pint-action from 1.0.0 to 2.3.0.

    Release notes

    Sourced from aglipanci/laravel-pint-action's releases.

    v2.3.0

    v2.2.0

    v2.1.0

    Fixing aglipanci/laravel-pint-action#1.

    v2.0.0

    Adding the ability to specify the Pint version on the configuration file.

    Commits
    • 859b17c Merge pull request #8 from likeadeckofcards/main
    • 2d7710d Add extended note to useComposer flag
    • 9594200 Add new flag for using the local project pint version
    • 1fce957 Get pint version from local composer
    • 0ac6db6 Merge pull request #7 from Nathanjms/patch-1
    • 859061e Update README.md
    • 8849e56 Merge pull request #5 from JKHarley/main
    • c412b9a add input
    • 47f7a28 format change
    • 5f15f8d change to formatting and add description
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    opened by dependabot[bot] 1
  • Bump dependabot/fetch-metadata from 1.5.0 to 1.5.1

    Bump dependabot/fetch-metadata from 1.5.0 to 1.5.1

    Bumps dependabot/fetch-metadata from 1.5.0 to 1.5.1.

    Release notes

    Sourced from dependabot/fetch-metadata's releases.

    v1.5.1

    What's Changed

    Bugfix:

    Dep bumps that are trivial so decided to keep this a patch release:

    Internal-facing infra changes:

    Full Changelog: https://github.com/dependabot/fetch-metadata/compare/v1...v1.5.1

    Commits
    • cd6e996 v1.5.1 (#384)
    • 64bd9b8 Fix library parser to trim trailing LF (#380)
    • 0908fa1 Merge pull request #382 from dependabot/dependabot/npm_and_yarn/types/node-20...
    • 2624edc Bump @​types/node from 20.2.1 to 20.2.3
    • d1defa4 Switch to using an app token instead of a PAT (#362)
    • cb17c9e Merge pull request #379 from dependabot/dependabot/npm_and_yarn/yargs-17.7.2
    • c6f9c16 Bump yargs from 17.7.1 to 17.7.2
    • 0f53327 Merge pull request #378 from dependabot/dependabot/npm_and_yarn/eslint-depend...
    • 398ed41 Bump the eslint-dependencies group with 2 updates
    • 801acab Merge pull request #375 from dependabot/dependabot/npm_and_yarn/eslint-depend...
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    opened by dependabot[bot] 1
Releases(v1.1.1)
Owner
Mohammed Manssour
A freelancer full-stack developer based in Dubai Interested in #Nodejs,#PHP,#WordPress and Machine Learning
Mohammed Manssour
Another initiative where patient in need of Blood and recovered patients willing to donate Blood can come together under one platform and connect with each other.

This is yet another initiative where patient in need of Blood and recovered patients willing to donate Blood can come together under one platform and connect with each other.

Rohit Tiwari 1 May 5, 2022
A PocketMine-MP plugin that allows you to comfortably register events using a new piece of PHP 8 power — attributes.

AdvancedEvents This is a PocketMine-MP plugin that allows you to comfortably register events using a new piece of PHP 8 power — attributes. Inspired b

JuraSciix 7 Dec 5, 2022
Configure Magento 2 to send email using Google App, Gmail, Amazon Simple Email Service (SES), Microsoft Office365 and many other SMTP (Simple Mail Transfer Protocol) servers

Magento 2 SMTP Extension - Gmail, G Suite, Amazon SES, Office 365, Mailgun, SendGrid, Mandrill and other SMTP servers. For Magento 2.0.x, 2.1.x, 2.2.x

MagePal :: Magento Extensions 303 Oct 7, 2022
Install an execute script of specify quality tools to your git pre-commit hook, and it executes only for changed files

Quality Hook Installer Install an execute script of specify quality tools to your git pre-commit hook, and it executes only for changed files Install

Kay W. 2 Dec 15, 2022
A data transfer object inspired by Rust's serde

Data Transfer Object Want to deserialize an object with data on the fly? Go for it by using the From trait. How is this package any different from spa

Randy Schütt 37 Dec 15, 2022
Casters for spatie/data-transfer-object

A package containing DTO casters Installation You can install the package via composer: composer require morningtrain/data-transfer-object-casters Usa

Morningtrain 3 Mar 8, 2022
Very flexible git hook manager for php developers

CaptainHook CaptainHook is an easy to use and very flexible git hook library for php developers. It enables you to configure your git hook actions in

CaptainHook 812 Dec 30, 2022
Hook-logger-plugin - Debug WordPress action / filter hooks.

hook-logger-plugin Easily debug WordPress action / filter hooks, finding where actions are called from and understanding the flow of execution. This p

bruce aldridge 4 Feb 5, 2022
A simple, standalone, modern PHP class inspector and mapper library, wrapping PHPs native reflection in a fluent interface

A simple, standalone, modern PHP class inspector and mapper library, wrapping PHPs native reflection in a fluent interface.

smpl 9 Sep 1, 2022
Makes water in cauldrons boil when there's fire under it and allows players to cook food in the boil

BoilingCauldrons Makes water in cauldrons boil when there's fire under it and allows players to cook food in the boil • Description • Planned Features

Spice 6 Apr 17, 2022