Created
February 16, 2023 14:50
-
-
Save stevebauman/020deb9efa9deb687a3a8abced243354 to your computer and use it in GitHub Desktop.
Mutable Observers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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