Laravel: Difference App::bind and App::singleton

后端 未结 3 387
無奈伤痛
無奈伤痛 2020-12-23 13:15

I get a bit confused over all the nice things laravel has to offer in terms of the IOC container and facades. Since I\'m not an experienced programmer it gets overwhelming t

3条回答
  •  旧巷少年郎
    2020-12-23 13:37

    But somewhere I read that Laravel treats classes called via facades always as singletons?

    Thereby, I encountered this problem:

    I have a demo class normally bound via

    $this->app->bind('demo', function() { return new Demo(); }

    An sett up a facade

    protected static function getFacadeAccessor() { return 'demo'; }

    The class itself looks like this

    class Demo 
        {
    
            private $value1;        
            private $value2;        
    
            public function setVal1($value)
            {
                $this->value1 = $value;
            }
    
            public function setVal2($value)
            {
                $this->value2 = $value;
            }
    
            public function getVals()
            {
                return 'Val 1: ' . $this->value1 . ' Val 2: ' . $this->value2;
            }   
    
        }

    You told me that if I would use a facade on this class, it would instantiate an object of the class and then call the method on that object.

    Butt I tested some more and found this very strange (at least to me) behavior:

    If I do

    Demo::setVal1('13654');
    and

    Demo::setVal2('random string')

    I shouldn't be able to use Demo::getVals() to retrieve the values I just created, should I? Since every time a facade method is used a new object will be instantiated and how can one object retrieve properties of another object? There should be three different instances but still I'm able to retrieve the properties from those other instances...

提交回复
热议问题