Getting Started

What is Siglot

Signals and slots is a mechanism introduced in Qt for communication between objects. It makes it easy to implement the observer pattern while avoiding boilerplate code. Siglot aims to provide similar features for the PHP language, with particular attention to Developer Experience (DX):

  • Easy to write, utilizing the first-class callable syntax
  • Compatible with existing auto-completion
  • Compatible with static analysis tools
  • No side effects with references

It can be regarded as an alternative to callbacks or event dispatchers, and it’s particularly suited for event-driven programming, to decouple events’ sender and receiver.

Installation

To install Siglot, you can use Composer:

composer require bviguier/siglot

Example

Let’s define a $button object, with a $button->clicked() signal function that can be triggered with the $button->click() function.

$button = new class() implements Siglot\Emitter {
    use Siglot\EmitterHelper;

    // This is our signal
    public function clicked(): Siglot\SignalEvent
    {
        return Siglot\SignalEvent::auto();
    }
    
    // This function triggers the signal above
    public function click(): void
    {
        $this->emit($this->clicked());
    }
};

Now let’s create a $receiver object, with a $receiver->onClick() method that will be used as a slot.

$receiver = new class() {
    // This is our slot
    public function onClick(): void
    {
        echo "Button clicked!\n";
    }
};

We can now connect the $button->clicked() signal to the $receiver->onClick() slot.

Siglot\Siglot::connect0(
    $button->clicked(...),
    $receiver->onClick(...),
);

Now, each time the signal is triggered with the $button->click() method, the connected slot will be called.

$button->click();
// Displays: Button clicked!