Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how laravel singleton pattern mange to reflect the changes on subsequent calls?

As all we know the singleton concept is very useful for us. But some of the underlying concept makes me scratch my head.

say we bind one object as singleton in the following way.

$this->app->singleton(Singleton::class, function () {
            return new Singleton();
        });

now as we know the object will only be resolved once and then it will be saved in the container's instances class property and return in the following way

if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
            return $this->instances[$abstract];
        }

okay everything fine till now.now we are modifying the instance from a controller

function index(){
   $abc = app(Singleton::class);
   $abc->a = 'b;
}

and we are accessing the singleton on other function

function test(){
   echo app(Singleton::class)->a;
}

and of course we can see it prints 'b'. But actually what we are doing in index function is saving the singleton to a variable $abc and we are modifying that variable in which I suppose reside a copy of the singleton object from the container's singleton array since laravel just return a value from its container instances array with index matches to the class name.

but how laravel manage it to reflect the change on next function when we are resolving the singleton object as above change only affects the $abc variable.

I am sure the answer could make me laugh as I am sure I have missed something in my way of thinking.

like image 356
fayis003 Avatar asked Oct 29 '22 17:10

fayis003


1 Answers

No, object instances are passed by reference.

app(Singleton::class) does not create a copy, it always returns (a reference to) the one and only instance of Singleton::class.

like image 190
RandomSeed Avatar answered Nov 15 '22 07:11

RandomSeed