Last active
November 23, 2022 14:41
-
-
Save meigwilym/350a6906f59a8c310524c2d4e34ee626 to your computer and use it in GitHub Desktop.
An abstract DTO class I've been experimenting with recently.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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