Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created June 30, 2020 12:01
Show Gist options
  • Save kobus1998/55fe1e45b35645c3d69d1484c32b6cda to your computer and use it in GitHub Desktop.
Save kobus1998/55fe1e45b35645c3d69d1484c32b6cda to your computer and use it in GitHub Desktop.
view model example
<?php
class ViewModel
{
public $title;
public $lang;
public $translations = [];
public $data = [];
public function t($key)
{
return !empty($this->translations[$this->lang][$key])
? $this->translations[$this->lang][$key]
: $key;
}
public function serve()
{
echo $this->title . "\n";
foreach($this->data as $key => $value)
{
echo "{$this->t($key)}: $value\n";
}
}
}
class User
{
public static function fromArray(array $a)
{
$user = new self;
foreach($a as $key => $value)
{
$user->{$key} = $value;
}
return $user;
}
}
class UserDetailViewModel extends ViewModel
{
public $name;
public $email;
public $phone;
public $translations = [
'nl' => [
'name' => 'naam',
'email' => 'email adres',
'phone' => 'telefoon nummer'
]
];
public function __construct($lang, User $user)
{
$this->lang = $lang;
$this->title = 'User view';
$this->data['name'] = $user->name;
$this->data['email'] = $user->email;
$this->data['phone'] = $user->phone;
}
}
$user = User::fromArray([
'name' => 'a',
'email' => 'a@a.a',
'phone' => 123
]);
$view = new UserDetailViewModel('nl', $user);
$view->serve();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment