I
I
Igor2022-03-25 15:42:10
Software design
Igor, 2022-03-25 15:42:10

How to properly implement Laravel Service Provider?

Now I'm getting a 500 error. Is everything correct at this stage or is it causing a loop? How to correctly pass the main class to the subordinates?

Created a service provider:

class LaraShopServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(LaraShop::class, function($app) {
            return new LaraShop($app->make(CartInterface::class), $app->make(OrderInterface::class));
        });

        $this->app->bind(CartInterface::class, function($app) {
            return new CartHandler($app->make(LaraShop::class));
        });

        $this->app->bind(OrderInterface::class, function($app) {
            return new OrderHandler($app->make(LaraShop::class));
        });
    }
}

Added it to config/app.php in the providers section. Below is the abbreviated class code.
LaraShop:

class LaraShop
{
    public function __construct(CartInterface $cart, OrderInterface $order)
    {
        $this->cart = $cart;
        $this->order = $order;
    }


CartHandler:

class CartHandler implements CartInterface
{
    public function __construct(LaraShop $laraShop)
    {
        $this->larashop = $laraShop;
    }
}


OrderHandler:

class OrderHandler implements OrderInterface
{
    public function __construct(LaraShop $laraShop)
    {
        $this->larashop = $laraShop;
    }
}


livewire component:

<?php

namespace App\Http\Livewire;

use App\Components\Larashop\LaraShop;
use Livewire\Component;

class MiniCart extends Component
{
    protected $listeners = ['cartChanged' => 'render'];

    public function mount(LaraShop $larashop)
    {
        $this->larashop = $larashop;
    }

    public function render()
    {
        // $cartHandler = new CartHandler;
        return view('livewire.mini-cart', $this->larashop->cart->get());
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question