Created
April 3, 2018 12:51
-
-
Save itsjavi/980957fe92e89bc1ea27a23a849ef070 to your computer and use it in GitHub Desktop.
basic DTO concept in PHP
This file contains hidden or 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 | |
use Illuminate\Contracts\Support\Arrayable; | |
use Illuminate\Contracts\Support\Jsonable; | |
use JsonSerializable; | |
class AbstractDto extends ArrayableJsonableObject implements \ArrayAccess | |
{ | |
public function __construct(array $properties = []) | |
{ | |
foreach ($properties as $k => $v) { | |
$this->$k = $v; | |
} | |
} | |
final public function __get($name) | |
{ | |
throw new \Exception($this->getUndefinedErrorMessage("\${$name} property")); | |
} | |
final public function __set($name, $value) | |
{ | |
throw new \Exception($this->getUndefinedErrorMessage("\${$name} property")); | |
} | |
final public function __call($name, $arguments) | |
{ | |
throw new \Exception($this->getUndefinedErrorMessage("{$name}() method")); | |
} | |
final public function offsetExists($offset) | |
{ | |
return isset($this->$offset); | |
} | |
final public function offsetGet($offset) | |
{ | |
return $this->$offset; | |
} | |
final public function offsetSet($offset, $value) | |
{ | |
$this->$offset = $value; | |
} | |
final public function offsetUnset($offset) | |
{ | |
unset($this->$offset); | |
} | |
private function getUndefinedErrorMessage($name) | |
{ | |
return static::class . "::{$name} is not defined. Dynamic access is disabled for DTOs."; | |
} | |
} | |
class ArrayableJsonableObject implements Arrayable, Jsonable, JsonSerializable | |
{ | |
/** | |
* @return array | |
*/ | |
public function toArray() | |
{ | |
$obj = $this; | |
$public_properties_only = function () use ($obj) { | |
$vars = get_object_vars($obj); | |
foreach ($vars as $k => $v) { | |
if ($v instanceof Arrayable) { | |
$vars[$k] = $v->toArray(); | |
} | |
} | |
return $vars; | |
}; | |
return $public_properties_only(); | |
} | |
/** | |
* @param int $options | |
* | |
* @return string | |
*/ | |
public function toJson($options = 0) | |
{ | |
return json_encode($this, $options); | |
} | |
/** | |
* @return array|mixed | |
*/ | |
public function jsonSerialize() | |
{ | |
return $this->toArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment