Example WordPress user model
<?php | |
class User { | |
public $ID; | |
public $_user; | |
public $attributes = [ | |
'description', | |
'first_name', | |
'last_name', | |
'prefixed' => '_prefix_', | |
]; | |
public $virtual = [ | |
'email', | |
'fullName', | |
'username', | |
]; | |
public function __construct($ID = null) { | |
$this->ID = $ID ?? self::id(); | |
$this->_user = new WP_User($this->ID); | |
foreach ($this->attributes as $k => $v) { | |
$attribute = is_string($k) ? $k : $v; | |
$prefix = is_string($k) ? $v : ''; | |
$this->$attribute = $this->meta($attribute, $prefix); | |
} | |
} | |
public function __get($attribute) { | |
if (in_array($attribute, $this->attributes)) { | |
return $this->attribute; | |
} elseif (in_array($attribute, $this->virtual)) { | |
return call_user_func([$this, '_get' . ucfirst($attribute)]); | |
} | |
} | |
public function _getEmail() { | |
return $this->_user->user_email; | |
} | |
public function _getFullName() { | |
return $this->first_name . ' ' . $this->last_name; | |
} | |
public function _getUsername() { | |
return $this->_user->user_login; | |
} | |
public function meta($key, $prefix = '_prefix_') { | |
return get_user_meta($this->ID, $prefix . $key, true); | |
} | |
public function setMeta($key, $value = null, $prefix = '_prefix_') { | |
return update_user_meta($this->ID, $prefix . $key, $value); | |
} | |
public static function id() { | |
return get_current_user_id(); | |
} | |
public static function loggedIn() { | |
return is_user_logged_in(); | |
} | |
public static function find($user_id = null) { | |
return new self($user_id); | |
} | |
public static function current() { | |
return new self(); | |
} | |
public static function getByLogin($login) { | |
if (is_email($login) && ! username_exists($login)) { | |
$user = get_user_by('email', $login); | |
} else { | |
$user = get_user_by('login', $login); | |
} | |
if ($user) { | |
return new self($user->ID); | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment