1

I have set up a listener by adding it in EventServiceProvider

protected $subscribe = [
  MyListener::class
];

The listener (MyListener) has a subscribe function that subscribes to the events the listener wants to listen for - and it works fine.


Now, I'm trying to add a check to restrict which events should be listened to. Something like

public function subscribe($events)
{
    $config = ConfigService::getUserConfig();

    if ($config->shouldSubscribe) {
       $events->listen(.....);
    }
}

I'm having some issues after adding this logic however.

It seems that when running composer install it executes the subscribe method.

This causes an issue, because there is no active session when running composer install - so I'm met with a SQL error - it can't find which database to search for configuration in - followed by this error

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

How can I conditionally subscribe to certain events in the listener?

Daniel
  • 10,641
  • 12
  • 47
  • 85

1 Answers1

1

It is not the exact response for your answer, but it should work in your case. You can detect if your code is running from console by using Application::runningInConsole() function.

Example:

public function subscribe($events)
{
    // Running from cli script, abort ship!
    if(app()->runningInConsole())
    {
        return;
    }

    $config = ConfigService::getUserConfig();

    if ($config->shouldSubscribe) {
       $events->listen(.....);
    }
}
Neproify
  • 131
  • 4
  • Very good idea, but runningInConsole also blocks regular artisan commands, where I would still want them subscribed. I wonder if there is a way to only block "composer" things – Daniel Aug 04 '19 at 08:47
  • Could you send me output of this code when running composer install? ```var_dump($argv);``` First element should be the name of script. If I'm thinking correct it should be composer. – Neproify Aug 04 '19 at 09:19