0

I'm trying to transform the following piece of code into a Facade. But I don't know how to call $this in the facade. I want to do this without using $this or passing it as a parameter. Can I somehow dependency inject it?

The following piece of code is inside a livewire component which will dispatch event to show a toast by a JS listener.

//turn this
$this->dispatchBrowserEvent('showToast', ['name'=>'success','title' => 'Updated','message'=>'Your data is saved']);
//into this
        
 $toast::success('Updated','Your data is saved');

How can I simplify this code?

1 Answers1

0

I usually create a trait Toast.

trait Toast 
{
    public function successAlert(string $title, string $message)
    {
         $this->dispatchBrowserEvent('showToast', [
              'name' => 'success',
              'title' => $title,
              'message' => $message,
         ])
    }
}

Then on my livewire component I use:

class MyComponent extends Component 
{
     use Toast;

     public function save()
     {
          // save
          $this->successAlert('Updated','Your data is saved'); 
     }
}

I couldn't think in an easy way to implement the facade, since you need to access internal features of the livewire component to dispatch the browser event.

itepifanio
  • 572
  • 5
  • 16