Skip to content

Instantly share code, notes, and snippets.

@stevebauman
Created February 16, 2023 14:50
Show Gist options
  • Save stevebauman/020deb9efa9deb687a3a8abced243354 to your computer and use it in GitHub Desktop.
Save stevebauman/020deb9efa9deb687a3a8abced243354 to your computer and use it in GitHub Desktop.
Mutable Observers
<?php
namespace App\Observers;
trait Mutable
{
public static function mute(string|array $events = null)
{
if (is_null($events)) {
$events = ['*'];
}
if (! is_array($events)) {
$events = [$events];
}
app()->instance(static::class, new ObserverEventProxy(
app(static::class), $events
));
}
public static function unmute()
{
app()->forgetInstance(static::class);
}
<?php
namespace App\Observers;
use Illuminate\Support\Traits\ForwardsCalls;
class ObserverEventProxy
{
use ForwardsCalls;
public function __construct(
protected object $observer,
protected array $events = []
){
}
public function __call(string $method, array $parameters)
{
if ($this->isMuted($method)) {
return null;
}
return $this->forwardCallTo(
$this->observer, $method, $parameters
);
}
protected function isMuted(string $method)
{
return in_array('*', $this->events)
|| in_array($method, $this->events);
}
}
<?php
UserObserver::mute();
User::create('...');
UserObserver::unute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment