roadrunner-php / laravel-bridge

🌉 RoadRunner ⇆ Laravel bridge 🇺🇦❤️
https://roadrunner.dev/docs/integration-laravel
MIT License
372 stars 25 forks source link

Service Container -> Binding A Singleton #90

Closed nitrogenium closed 2 years ago

nitrogenium commented 2 years ago

A clean installation of this repository, but:

.rr.local.yml

  # Workers pool settings.
  pool:
    # How many worker processes will be started. Zero (or nothing) means the number of logical CPUs.
    #
    # Default: 0
    num_workers: 2

MyCounter.php

<?php

namespace App\Singleton;

use Illuminate\Support\Facades\Log;

class MyCounter
{

    protected int $counter=0;

    public function __construct()
    {
        Log::debug('MyCounter __construct');

    }

    public function __destruct ()
    {
        Log::debug('MyCounter __destruct');
    }

    public function increment(): int
    {
         Log::debug('++');
         return ++$this->counter;
    }

}

In AppServiceProvider


    public function register()
    {
        $this->app->singleton('mc', function () {
            return new MyCounter();
        });
    }

In welcome.blade.php

   {{ app()->make('mc')->increment() }}

In the log file each request:

[2022-02-21 06:10:56] local.DEBUG: MyCounter __construct
[2022-02-21 06:10:56] local.DEBUG: ++
[2022-02-21 06:10:56] local.DEBUG: MyCounter __destruct

Obviously, the counter is reset every time. Why? What am I doing wrong?

What power kills my singleton "mc"?

tarampampam commented 2 years ago

Greetings again, thanks for your issue!

The singleton will persist during the HTTP request processing and will be re-created for the next request (you can test it with the multiple calling increment() method in your view). Also, you can read this interesting article.

But, if you want to have a "true" singleton - you should make an instance of your container before the requests processing, e.g. put it into the warm section in the configuration file:

diff --git a/config/roadrunner.php b/config/roadrunner.php
index 3ad3f8c..8cc3a88 100644
--- a/config/roadrunner.php
+++ b/config/roadrunner.php
@@ -80,6 +80,7 @@

     'warm' => [
         ...Defaults::servicesToWarm(),
+        'mc',
     ],

     'clear' => [

This issue can be closed?

nitrogenium commented 2 years ago

Thank you for your reply. No more questions. I'm even a little ashamed that I did not look in the Spiral\RoadRunnerLaravel\Worker.php - all the answers are there.

Thanks for the awesome package.