Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running code on Symfony kernel initialisation

Tags:

php

symfony

How can some code in a bundle be executed after booting the Symfony2 kernel?

  • The code must be run before a request is handled or console command is run.
  • The code must be executed once, even when the kernel handles multiple requests during its lifetime.
  • The code must be able to access the bundle configuration. It may therefore not be run to early in the proces.

The reason I need this is that I need to register a stream wrapper. I need to be able to use the bundle configuration since the stream wrapper definitions are defined in the config.

I tried the following:

  • Implementing the constructor of the bundle class. (This does not work, not all bundles are initialised at this point)
  • Creating event listeners for kernel.request and console.command (This will cause the code to be executed multiple times when the kernel handles multiple requests during its lifetime.)
like image 514
Xatoo Avatar asked Dec 08 '22 03:12

Xatoo


2 Answers

You can override the boot method of your bundle.

class MyBundle extends Bundle
{
    public function boot()
    {

    }
}
like image 85
Flosculus Avatar answered Dec 10 '22 23:12

Flosculus


You can register one service as event listener for both kernel.request and console.command. It will be fired from console and from HTTP request.

like image 27
Michael Sivolobov Avatar answered Dec 10 '22 22:12

Michael Sivolobov