Skip to content

Instantly share code, notes, and snippets.

@eezhal92
Last active March 19, 2016 09:16
Show Gist options
  • Save eezhal92/a92196d23f0d59dc158d to your computer and use it in GitHub Desktop.
Save eezhal92/a92196d23f0d59dc158d to your computer and use it in GitHub Desktop.
<?php
namespace App;
class Company extends Entity
{
/**
* @var int
*/
protected $id;
/**
* @var string
*/
private $name;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
* @return void
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
* @return void
*/
public function setName($name)
{
$this->name = $name;
}
}
<?php
namespace App;
use ReflectionClass;
use JsonSerializable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
abstract class Entity implements Arrayable, Jsonable, JsonSerializable
{
/**
*
* @var array
*/
protected $hidden = [];
/**
* Convert the object to array.
*
* @return array
*/
public function toArray()
{
return $this->getAttributes();
}
/**
* Convert the model instance to JSON.
*
* @return string
*/
public function toJson($options = 0)
{
return json_encode($this->getAttributes(), $options);
}
/**
* Convert the object into something JSON serializable.
*
* @return array
*/
public function jsonSerialize()
{
return $this->toArray();
}
/**
* Get object attributes exclude in hidden attribute.
*
* @return array
*/
private function getAttributes()
{
$reflection = new ReflectionClass(static::class);
$attributes = [];
foreach ($reflection->getProperties() as $property) {
$property->setAccessible(true);
if ($property->name != 'hidden' && ! in_array($property->name, $this->hidden)) {
$value = $property->getValue($this) ?: '';
$attributes[$property->name] = $value;
}
}
return $attributes;
}
}
<?php
use App\Company;
$company = new Company;
$company->setId(1);
$company->setName('Awesome Inc.');
// return $company->toArray();
// return $company;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment