|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Acme\App; |
| 4 | + |
| 5 | +abstract class User { |
| 6 | + |
| 7 | + /** |
| 8 | + * @var string |
| 9 | + */ |
| 10 | + protected $email; |
| 11 | + |
| 12 | + /** |
| 13 | + * @var string |
| 14 | + */ |
| 15 | + protected $password; |
| 16 | + |
| 17 | + /** |
| 18 | + * @var boolean |
| 19 | + */ |
| 20 | + protected $isAdmin = false; |
| 21 | + |
| 22 | + /** |
| 23 | + * All properties that can be set directly |
| 24 | + * @var array |
| 25 | + */ |
| 26 | + protected $fillable = array('email', 'password'); |
| 27 | + |
| 28 | + /** |
| 29 | + * All properties that can be gotten directly |
| 30 | + * @var array |
| 31 | + */ |
| 32 | + protected $accessible = array('email', 'password'); |
| 33 | + |
| 34 | + /** |
| 35 | + * Class configuration only |
| 36 | + * @param array $params |
| 37 | + */ |
| 38 | + public function __construct(Array $params = array()) { |
| 39 | + |
| 40 | + if (count($params)) { |
| 41 | + foreach ($params as $key => $value) { |
| 42 | + $this->$key = $value; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Directly set inaccessible but existing properties, if in $this->fillable array |
| 49 | + * @param string $name |
| 50 | + * @param mixed $value |
| 51 | + * @return void |
| 52 | + */ |
| 53 | + public function __set ($name, $value) { |
| 54 | + |
| 55 | + // Do not set if not fillable |
| 56 | + if (! in_array($name, $this->fillable)) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + |
| 60 | + if (isset($this->$name)) { |
| 61 | + $this->$name = $value; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Directly get inaccessible but existing properties, if in $this->accesible array |
| 67 | + * @param string $name |
| 68 | + * @return mixed |
| 69 | + */ |
| 70 | + public function __get ($name) { |
| 71 | + |
| 72 | + // Do not return if not accessible |
| 73 | + if (! in_array($name, $this->accessible)) { |
| 74 | + return NULL; |
| 75 | + } |
| 76 | + |
| 77 | + return isset($this->$name) ? $this->$name : NULL; |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * Return accessible properties as a json object |
| 82 | + * @return string |
| 83 | + */ |
| 84 | + public function __toString () { |
| 85 | + |
| 86 | + $data = array(); |
| 87 | + |
| 88 | + // Only add property accessible |
| 89 | + foreach ($this->accessible as $key) { |
| 90 | + $data[$key] = $this->$key; |
| 91 | + } |
| 92 | + |
| 93 | + return json_encode($data); |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Log in a user |
| 98 | + * @return string |
| 99 | + */ |
| 100 | + public function login(){ |
| 101 | + return 'Logging in a user ...'; |
| 102 | + } |
| 103 | + |
| 104 | + /** |
| 105 | + * Log in a user |
| 106 | + * @return string |
| 107 | + */ |
| 108 | + public function logout(){ |
| 109 | + return 'Logging out ...'; |
| 110 | + } |
| 111 | + |
| 112 | +} |
0 commit comments