I'm trying to make proper use of Laravel's Service Container to instantiate a connection to a third-party API and use it across my Controllers. Below I added my API connection into the register method of Laravel's AppServiceProvider. In my Controller constructor, I provide a handle to that connection that can be used freely inside the Controller wherever a connection is needed. Does this example demonstrate the best use of a Service Container? Should I replace my reference to 'bind' with 'singleton' instead?
use App\Http\Clients\RestClient;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(RestClient::class, function($app)
{
$this->api = new RestClient();
$this->api->setUrl(getenv('API_REST_URL'))
->setUsername(getenv('API_USERNAME'))
->setPassword(getenv('API_PASSWORD'))
->connect();
return $this->api;
});
}
}
class LoginController extends Controller
{
public function __construct(RestClient $api)
{
$this->api = $api;
}
public function postLogin()
{
$results = $this->api->search('Users');
}
}