Skip to content

Instantly share code, notes, and snippets.

@elminson
Created March 26, 2025 03:29
Show Gist options
  • Save elminson/5c6802cfa5c4044529586be19a4f11bd to your computer and use it in GitHub Desktop.
Save elminson/5c6802cfa5c4044529586be19a4f11bd to your computer and use it in GitHub Desktop.
<?php
namespace FerminNamespace\Traits;
use Symfony\Component\HttpClient\HttpClient;
use FerminNamespace\Traits\CustomPayPalHttpClient;
class PayPalService
{
use CustomPayPalHttpClient;
// Example method to show client usage
public function processPayment()
{
// Scenario 1: Using default client creation
$this->setClient();
// Now $this->client is created with default custom configuration
// Scenario 2: Passing a custom HttpClient
$customHttpClient = HttpClient::create([
'base_uri' => 'https://custom-specific-endpoint.com',
'headers' => [
'X-Custom-Header' => 'Custom Value'
]
]);
$this->setClient($customHttpClient);
// Now $this->client is set to the custom HttpClient
// Example of using the client (hypothetical)
$response = $this->client->request('GET', '/some-paypal-endpoint');
return $response;
}
// Demonstration method showing different client setups
public function demonstrateClientSetup()
{
// Create service instance
$paypalService = new self();
// Scenario 1: Default client creation
$paypalService->setClient();
// Scenario 2: Custom client creation
$customClient = HttpClient::create([
'timeout' => 15,
'base_uri' => 'https://alternative-paypal-endpoint.com'
]);
$paypalService->setClient($customClient);
return $paypalService;
}
}
// Example usage
$service = new PayPalService();
$service->setClient(); // Uses default configuration
```
Key points in this example:
1. The `PayPalService` class uses the `CustomPayPalHttpClient` trait
2. `setClient()` method can be called in two ways:
- Without arguments: Creates a default client
- With a custom `HttpClient`: Uses the provided client
3. The method returns `$this`, allowing method chaining
4. Demonstrates different scenarios of client setup
You can use it like this:
```php
// Create a service and set a default client
$paypalService = new PayPalService();
$paypalService->setClient();
// Or create with a custom client
$customClient = HttpClient::create([...]);
$paypalService->setClient($customClient);
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment