Answer the question
In order to leave comments, you need to log in
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
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;
}
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;
}
}
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()
{
//
}
}
namespace App\Http\Controllers;
use App\Contract\PaymentInterface;
class PaymentController
{
public function getPayment(PaymentInterface $payment)
{
dd($payment->pay());
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question