Skip to content

Instantly share code, notes, and snippets.

@meigwilym
Last active November 23, 2022 14:41
Show Gist options
  • Save meigwilym/350a6906f59a8c310524c2d4e34ee626 to your computer and use it in GitHub Desktop.
Save meigwilym/350a6906f59a8c310524c2d4e34ee626 to your computer and use it in GitHub Desktop.
An abstract DTO class I've been experimenting with recently.
<?php
namespace App\DTO;
use Illuminate\Support\Str;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
/**
* An abstract class to provide out of the box functionality for DTO objects.
*
* DTOs use camel case properties, as they look nicer.
* This class returns properties in arrays or json as snake case (to match DB fields)
*
*/
abstract class AbstractDTO implements Jsonable, Arrayable
{
public function __construct(array $data = [])
{
foreach ($data as $key => $datum) {
$this->set($key, $datum);
}
}
public function toArray()
{
$ar = [];
foreach ($this->getProperties() as $key) {
if (isset($this->$key)) {
$ar[Str::snake($key)] = $this->get($key);
}
}
return $ar;
}
public function toJson($options = 0)
{
return json_encode($this->toArray(), $options);
}
public function __get($name)
{
return $this->get($name);
}
public function get($name)
{
$property = Str::camel($name);
if (property_exists($this, $property)) {
return $this->{$property};
}
throw new \Exception('Property ' . $property . ' does not exist on ' . get_class($this));
}
public function __set($name, $value)
{
return $this->set($name, $value);
}
public function set($name, $value)
{
$property = Str::camel($name);
if (!property_exists($this, $property)) {
throw new \Exception('Can\'t set property ' . $property . ' that does not exist on ' . get_class($this));
}
$this->{$property} = $value;
}
private function getProperties()
{
return array_keys(get_object_vars($this));
}
}
<?php
namespace App\DTO;
class Client extends AbstractDTO
{
public $name;
public $slug;
public $notes = '';
public $isActive = true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment