R
R
rolegox2019-06-02 12:27:06
Laravel
rolegox, 2019-06-02 12:27:06

How to use the service container in your classes?

How can I use the features of the Laravel container service in my classes (eg App\Serivces\Payment)? If I specify some class in the method parameters, then when the method is called, an error occurs that you need to pass this class to it yourself, but in the controllers the container works, but it no longer sees its classes.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav, 2019-06-02
@mzcoding

So! Let's say you have some entity for working with payments, let's call it Payment
1. We create a contract and describe (let's say) the pay method responsible for (let's say) generating a payment link:

namespace App\Contract;

interface PaymentInterface
{
   public function pay(): string;
}

2. We create the Payment service and implement our interface + describe the pay method and create another constructor that (let's say) accepts some link to pay (of the payment system) - We'll take the link (let's say from the config):
namespace App\Service;

use App\Contract\PaymentInterface;

class Payment implements PaymentInterface
{
    protected $paymentLink;

    public function __construct($paymentLink)
    {
        $this->paymentLink = $paymentLink;
    }

    public function pay(): string
    {
        return (string)$this->paymentLink;
    }
}

3. Create a provider: php artisan make:provider PaymentProvider :
namespace App\Providers;

use App\Contract\PaymentInterface;
use App\Service\Payment;
use Illuminate\Support\ServiceProvider;

class PaymentProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(PaymentInterface::class, function ($app) {
            return new Payment(config('app.payment_link'));
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

4. Now we need to register our provider in the config (config/app.php) - providers array (to the end):
5. Write the payment_link parameter in config/app.php : 6. Now create a controller (or call it in an existing one):
namespace App\Http\Controllers;

use App\Contract\PaymentInterface;

class PaymentController
{
    public function getPayment(PaymentInterface $payment)
    {
        dd($payment->pay());
    }

}

7. Done)
P.S: Please note that we accept an interface as input, not an implementation
P.P.S: You can also call it in any class that is registered in the container.
P.P.P.S: You can use bindings without an interface (read in the doc)
You can also call your class via the resolve helper (read in the doc)
Link to the doc: https://laravel.com/docs/5.8/ container

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question