Skip to content

Instantly share code, notes, and snippets.

@nickalcala
Created March 16, 2019 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickalcala/9f24773ab655b1d2e4583abe7422cef4 to your computer and use it in GitHub Desktop.
Save nickalcala/9f24773ab655b1d2e4583abe7422cef4 to your computer and use it in GitHub Desktop.
Laravel View-models
<?php
namespace App\ViewModels;
abstract class ViewModel
{
protected $mappings = [];
/**
* Map an array to the view-model's properties.
*
* @param $values
* @return ViewModel
*/
public function mapArray($values)
{
foreach ($this->mappings as $index => $mapping) {
if (is_array($mapping)) {
if (count($mapping) == 3 && $mapping[2] == 'array') {
foreach ($values[$mapping[1]] as $index2 => $value) {
/* @var $vm ViewModel */
$vm = new $mapping[0]();
$this->$index[] = $vm->mapArray($value);
}
} else {
/* @var $vm ViewModel */
$vm = new $mapping[0]();
$this->$index = $vm->mapArray(@$values[$mapping[1]]);
}
} else {
$this->$index = @$values[$mapping];
}
}
return $this;
}
/**
* Turn view model into associative array with mapping as keys.
*
* @return array
*/
public function toArray()
{
$result = [];
foreach ($this->mappings as $index => $mapping) {
if (is_array($mapping)) {
if (count($mapping) == 3 && $mapping[2] == 'array') {
foreach ($this->$index as $index2 => $value) {
/* @var ViewModel $value */
$result[$mapping[1]] = $value->toArray();
}
} else {
$result[$mapping[1]] = $this->$index->toArray();
}
} else {
$result[$mapping] = $this->$index;
}
}
return $result;
}
function __get($name)
{
if (empty($this->$name)) {
return null;
}
return $this->$name;
}
function __set($name, $value)
{
$this->$name = $value;
}
}
@nickalcala
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment