Replies: 1 comment 8 replies
-
|
Just found that I can implement it in my application by overriding model methods, but it would be nice if it becomes a framework feature. <?php
namespace App\Models\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_PROPERTY)]
class AttributeHook {}<?php
namespace App\Models\Concerns;
use App\Models\Attributes\AttributeHook;
use Override;
use PropertyHookType;
use ReflectionProperty;
trait HasHookMutator
{
protected static $hookMutatorCache = [];
#[Override]
public function hasGetMutator($key)
{
return $this->hasHookMutator($key, PropertyHookType::Get) || parent::hasGetMutator($key);
}
#[Override]
protected function mutateAttribute($key, $value)
{
if ($this->hasHookMutator($key, PropertyHookType::Get)) {
return $this->{$key};
}
return parent::mutateAttribute($key, $value);
}
#[Override]
public function hasSetMutator($key)
{
return $this->hasHookMutator($key, PropertyHookType::Set) || parent::hasSetMutator($key);
}
#[Override]
protected function setMutatedAttributeValue($key, $value)
{
if ($this->hasHookMutator($key, PropertyHookType::Set)) {
return $this->{$key} = $value;
}
return parent::setMutatedAttributeValue($key, $value);
}
protected function hasHookMutator(string $key, PropertyHookType $type)
{
$class = \get_class($this);
$cache = &static::$hookMutatorCache["{$class}:{$key}:{$type->name}"];
if (isset($cache)) {
return $cache;
}
if (!property_exists($this, $key)) {
return $cache = false;
}
$property = new ReflectionProperty($this, $key);
if (!$property->hasHook($type) || !$property->getAttributes(AttributeHook::class)) {
return $cache = false;
}
return $cache = true;
}
} |
Beta Was this translation helpful? Give feedback.
8 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
It would be great if I can write Accessors and Mutators like this
and get it recognized by serialization (appends/hidden).
The framework can distinguish them from other properties with the
AttributeHookattribute.Benefits:
Beta Was this translation helpful? Give feedback.
All reactions