0

I have a singleton setup in my AppServiceProvider.php, such as this:

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

    View::composer(['partials.*'], function($view){
        $view->with('breadcrumbs', new Breadcrumbs());
    });

}

Breadcrumbs is just a simple class that manages an array of breadcrumbs and I want there only to be 1 object across the whole app (so every time you call new Breadcrumbs() you actually get the existing object, not a new one. (i think this is what singletons are for?)

But now have added this to the JetStreamServiceProvider.php

public function boot()
{
        $this->configurePermissions();

        Fortify::loginView(function (){
            $breadcrumbs = new Breadcrumbs();
            $breadcrumbs->add('login','login.php');
            return view('auth.login');
        });
}

However instead of using the same object as what was created in the AppServiceProvider it is making a new object (so the breadcrumbs object in AppServiceProvider and the breadcrumbs object in the JetStreamServiceProvider are 2 different objects containing a different set of data)...which is no good.

What am I doing wrong?

David B
  • 400
  • 2
  • 15

2 Answers2

2

If you want to resolve the binding you setup you need to use the IoC container that you set the binding on to resolve it. You calling new Class is you telling PHP directly to create a new instance of that class. Laravel does not change how PHP works.

public function register()
{
    $this->app->singleton(Breadcrumbs::class, function () { ... });
}

public function boot()
{
    View::composer(['partials.*'], function ($view) {
        // resolve the instance from the IoC (Application) Container
        $view->with('breadcrumbs', $this->app->make(Breadcrumbs::class));
    });

    // you can do a "view share" to share this with all views instead:
    View::share('breadcrumbs', $this->app->make(Breadcrumbs::class));
}



Fortify::loginView(function () {
    $this->app->make(Breadcrumbs::class)->add('login', 'login.php');
    return view('auth.login');
});

Laravel 8.x Docs - Service Container - Resolving - The make method

lagbox
  • 48,571
  • 8
  • 72
  • 83
0

This was the solution I used:

AppServiceProvider

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

public function boot(Breadcrumbs $breadcrumbs)
{
        View::composer(['partials.*'], function($view) use ($breadcrumbs){
            $view->with('breadcrumbs', $breadcrumbs);
        });

}

JetStreamServiceProvider.php

public function boot(Breadcrumbs $breadcrumbs)
{
    Fortify::loginView(function () use ($breadcrumbs){
        $breadcrumbs->add('Login',Route('login'));
        return view('auth.login');
    });
}
David B
  • 400
  • 2
  • 15