Created
June 30, 2020 12:01
-
-
Save kobus1998/55fe1e45b35645c3d69d1484c32b6cda to your computer and use it in GitHub Desktop.
view model example
This file contains hidden or 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 | |
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' => '[email protected]', | |
'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