Last active
April 14, 2016 11:14
-
-
Save eimihar/e03a0ff71b4a148ca343a504596f39be to your computer and use it in GitHub Desktop.
extended eloquent model
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\Entity; | |
abstract class Base extends \Illuminate\Database\Eloquent\Model | |
{ | |
protected static function apiFields() | |
{ | |
return array(); | |
} | |
public function toApiModel(array $fields = array(), array $additionals = array()) | |
{ | |
$data = array(); | |
$onlySelected = count($fields) > 0; | |
$apiFields = static::apiFields(); | |
if(count($apiFields) == 0) | |
$apiFields = array_keys($this->getAttributes()); | |
foreach($apiFields as $field) | |
{ | |
if($onlySelected) | |
if(!in_array($field, $fields)) | |
continue; | |
$value = $this->$field; | |
if($value instanceof Base) | |
$data[$field] = $value->toApiModel(); | |
else | |
$data[$field] = $value; | |
} | |
foreach($additionals as $key => $value) | |
{ | |
if($onlySelected) | |
{ | |
if(!in_array($key, $fields)) | |
continue; | |
} | |
$data[$key] = $value; | |
} | |
return $data; | |
} | |
public function getAttribute($key) | |
{ | |
$inAttributes = array_key_exists($key, $this->attributes); | |
// If the key references an attribute, we can just go ahead and return the | |
// plain attribute value from the model. This allows every attribute to | |
// be dynamically accessed through the _get method without accessors. | |
if ($inAttributes || $this->hasGetMutator($key)) | |
{ | |
return $this->getAttributeValue($key); | |
} | |
// If the key already exists in the relationships array, it just means the | |
// relationship has already been loaded, so we'll just return it out of | |
// here because there is no need to query within the relations twice. | |
if (array_key_exists($key, $this->relations)) | |
{ | |
return $this->relations[$key]; | |
} | |
// If the "attribute" exists as a method on the model, we will just assume | |
// it is a relationship and will load and return results from the query | |
// and hydrate the relationship's value on the "relationships" array. | |
if (method_exists($this, $method = 'relate'.strtoupper($key))) | |
{ | |
return $this->getRelationshipFromMethod($method); | |
} | |
} | |
public function toArray(array $fields = array()) | |
{ | |
$data = parent::toArray(); | |
if(count($fields) == 0) | |
return $data; | |
$new = array(); | |
foreach($fields as $field) | |
{ | |
if($data[$field] instanceof Base) | |
$new[$field] = $data[$field]->toArray(); | |
else | |
$new[$field] = $data[$field]; | |
} | |
return $new; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment