Skip to content

Instantly share code, notes, and snippets.

@arashrasoulzadeh
Created September 2, 2019 22:00
Show Gist options
  • Save arashrasoulzadeh/82285acec55d6773de6313e60276defb to your computer and use it in GitHub Desktop.
Save arashrasoulzadeh/82285acec55d6773de6313e60276defb to your computer and use it in GitHub Desktop.
<?php
namespace arashrasoulzadeh\auth\src\traits;
use arashrasoulzadeh\auth\src\model\UserAuthMetas;
trait UserMetaTrait
{
/** @var array
* this keys will NOT be loaded from metas
*/
private $excludeInMeta = [
'id'
];
/** @var array
* used by caching system
*/
private $fieldCaches = [
];
/**
* load the key from database
* @param $key
* @return string|null
*/
public function loadFromDatabase($key)
{
$item = UserAuthMetas
::where("class", $this->table)
->where("key", $key)
->orderBy("id","desc")
->where("owner", $this->id);
if ($item->count()) {
$item = $item->first();
$fresh = $item->fresh();
return $fresh->value;
} else {
return null;
}
}
/**
* @inheritDoc
*/
public function __get($key)
{
$original = parent::__get($key);
if (!in_array($key, $this->excludeInMeta)) {
if (!isset($this->fieldCaches[$key])) {
$value = $this->loadFromDatabase($key);
$this->fieldCaches[$key] = $value;
return $this->fieldCaches[$key];
} else {
return $this->fieldCaches[$key];
}
} else {
return $original;
}
}
/**
* save the key to database
* @param $key
* @param $value
*/
private function saveToDatabase($key, $value)
{
$item = new UserAuthMetas();
$item->class = $this->table;
$item->owner = $this->id;
$item->key = $key;
$item->value = $value;
$item->save();
}
/**
* @inheritDoc
*/
public function __set($key, $value)
{
$original = parent::__get($key);
if (!in_array($key, $this->excludeInMeta)) {
$this->saveToDatabase($key, $value);
$this->fieldCaches[$key] = $value;
parent::__set($key, $value);
} else {
parent::__set($key, $value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment