Skip to content

Instantly share code, notes, and snippets.

@feelinc
Last active August 29, 2015 13:57
Show Gist options
  • Save feelinc/9406641 to your computer and use it in GitHub Desktop.
Save feelinc/9406641 to your computer and use it in GitHub Desktop.
<?php
return Response::json(new SettingTemplate($data));
<?php
class SettingTemplate extends Template
{
/**
* Prepare the data to retreive.
*
* @return void
*/
public function prepareData()
{
$this->setAttribute('key');
$this->setAttribute('value');
$this->setAttribute('created_at');
$this->setAttribute('updated_at');
}
}
<?php
use Illuminate\Database\Eloquent\Model;
use DateTime;
abstract class Template
{
/**
* The model.
*
* @var Model
*/
protected $model;
/**
* The attributes.
*
* @var array
*/
protected $attributes;
/**
* Create a new instance.
*
* @param Model $model
* @return void
*/
public function __construct(Model $model)
{
$this->model = $model;
$this->prepareData();
}
/**
* Return the model.
*
* @return Model
*/
public function getModel()
{
return $this->model;
}
/**
* Prepare the data to retreive.
*
* @return void
*/
public function prepareData()
{}
/**
* Get an attribute from the template.
*
* @param string $key
* @return mixed
*/
public function getAttribute($key)
{
if (isset($this->$key)) {
return $this->$key;
}
return '';
}
/**
* Set a given attribute on the template from model.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function setAttribute($key, $value = null)
{
if (is_null($value)) {
$value = $this->model->$key;
}
if ($value instanceof DateTime) {
$value = $value->format('c');
}
$this->$key = $value;
unset($value);
}
/**
* Dynamically retrieve attributes on the template.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->getAttribute($key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment