php - Laravel 5 Resolving dependencies in ServiceProvider -


i have class acts storage (add/get item). try bind singleton in 1 service provider, , resolve in another's boot method.

the code changed simplicity.

app/providers/bindingprovider.php

<?php namespace app\providers;  use illuminate\support\facades\facade; use illuminate\support\serviceprovider serviceprovider;  class mybindingfacade extends facade {     public static function getfacadeaccessor() {         return 'my.binding';     } }  class mybinding {      protected $items = [];      public function add($name, $item) {         $this->items[$name] = $item;     }     public function get($name) {         return $this->items[$name];     }     public function getall() {         return $this->items;     }  }  class bindingprovider extends serviceprovider {      public function register() {         $this->app->singleton('my.binding', function($app) {             return $app->make('app\providers\mybinding');         });     }      public function provides() {         return [             'my.binding',         ];     } } 

app/providers/resolvingprovider.php

<?php namespace app\providers;  use illuminate\support\serviceprovider serviceprovider; use app\providers\mybinding;  class resolvingprovider extends serviceprovider {      public function boot(mybinding $binding) {         $binding->add('foo', 'bar');          // $manual = $this->app->make('my.binding');         // $manual->add('foo', 'bar');     }      public function register() {}  } 

app/http/controllers/welcomecontroller.php

<?php namespace app\http\controllers;  use app\providers\mybindingfacade;  class welcomecontroller extends controller {      public function index()     {         dd(mybindingfacade::getall()); // debug items     } } 

when try debug mybinding state in welcomecontroller i'm getting empty item array. however, if uncomment $manual part resolvingprovider returns array containing 'foo' => 'bar'. mean ioc resolution broken in serviceprovider::boot() method or misusing laravel functionality?

laravel version: 5.0.28

update: added code sample welcomecontroller.

with this:

$this->app->singleton('my.binding', function($app) {     return $app->make('app\providers\mybinding'); }); 

you're saying: my.binding singleton , resolves instance of app\providers\mybinding.

that doesn't mean app\providers\mybinding registered singleton too. should instead this:

$this->app->singleton('app\providers\mybinding');  $this->app->bind('my.binding', function($app) {     return $app->make('app\providers\mybinding'); }); 

because facade binding uses $app->make() should same instance registered $this->app->singleton() right above.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -