Skip to content

Instantly share code, notes, and snippets.

@ricklancee
Last active August 29, 2015 14:23
Show Gist options
  • Save ricklancee/294aa89243255694daef to your computer and use it in GitHub Desktop.
Save ricklancee/294aa89243255694daef to your computer and use it in GitHub Desktop.
Easy -read only- access for a DTOs private properties.
<?php
final class Dto
{
use Gettable;
private $title;
private $description;
public function __construct($title, $description) {
$this->title = $title;
$this->description = $description;
}
public function getTitle()
{
return $this->title;
}
public function getDescription()
{
return $this->description;
}
}
<?php
use Exception;
use ReflectionClass;
trait Gettable
{
public function __get($name)
{
if (!property_exists($this, $name)) {
throw new Exception("Undefined property: ". get_class($this) ."::$".$name);
}
$property = (new ReflectionClass($this))->getProperty($name);
if ($property->isPrivate()) {
$getter = 'get' . ucfirst($name);
if (method_exists($this, $getter)) {
return $this->{$getter}();
}
throw new Exception("Trying to access private property ". get_class($this) ."::$".$name);
}
return $this->name;
}
}
<?php
$dto = new Dto(
'Alice\'s Adventures in Wonderland',
'Alice was beginning to get very tired of sitting by her sister on the bank, ...'
);
var_dump($dto->getTitle() === $dto->title); // true
var_dump($dto->getDescription() === $dto->description); //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment