# release-php-ga
Source: https://speakeasy.com/blog/release-php-ga


Following our successful beta release and the continued renaissance in the PHP ecosystem, we're thrilled to announce that Speakeasy's PHP SDK Generation is now generally available. This marks a significant milestone in our mission to provide developers with powerful, type-safe SDKs across all major programming languages.

## Key highlights:

- True type safety with PHP 8's robust type system
- Native support for BigInt & Decimal with arbitrary precision
- Built-in OAuth 2.0 flows with automatic token management
- Seamless Laravel integration with ready-to-use Service Providers
- Enhanced error handling with specialized exception types
- Intelligent pagination for handling large datasets

## Why PHP matters in 2025

With PHP powering over 75% of websites with known server-side languages and the explosive growth of PHP 8's adoption, PHP remains a cornerstone of modern web development. The language has transformed from its dynamic roots into a powerhouse of type safety and performance, with PHP 8.0-8.3 introducing features that rival traditionally "enterprise" languages:

```php
// The evolution of PHP type safety
// PHP 5 - No type hints
function process($data) { /* ... */ }

// PHP 7 - Basic scalar type hints
function process(array $data): array { /* ... */ }

// PHP 8 - Full type system with union types and nullability
function process(array $data, ?Logger $logger = null): array|JsonResponse 
{
    // Type-safe operations with IDE support
    return $data['success'] ? $data : new JsonResponse($data);
}
```

Modern PHP offers the perfect balance between developer productivity and enterprise-grade reliability, making it a great choice for today's development teams.

Our GA release brings production-ready PHP SDK generation to this thriving ecosystem, enabling API providers to deliver exceptional developer experiences to their PHP users.

## What we learned during the beta

During our beta phase, we gathered valuable feedback from PHP developers across industries. Three main themes emerged:

1. Framework compatibility was crucial - especially with Laravel
2. Type safety was consistently identified as the most important feature
3. Performance optimization remained a key concern for high-volume API users

We've addressed each of these areas in our GA release, with particular focus on framework integration and connection efficiency optimizations.

---

## What's new in our GA release

Building on our beta foundation, we've expanded our PHP SDK generation with powerful new capabilities:

### Core features

- **True Type Safety**: Leverage PHP 8's type system with proper docblocks for superior IDE integration
- **Union Types**: Represent complex data structures and polymorphic APIs with PHP 8's union type syntax
- **Laravel Integration**: Deploy framework-compatible packages with zero configuration required
- **OAuth 2.0**: Implement secure authentication flows with built-in token management
- **BigInt & Decimal**: Handle arbitrary precision numbers for financial and scientific applications

### Developer experience improvements

- **Deep Object Support**: Pass complex nested objects in query parameters without serialization headaches
- **Smart Pagination**: Navigate large datasets with intuitive iterators that handle pagination automatically
- **Resilient Networking**: Implement robust retry mechanisms for handling transient API failures
- **Extensible SDK Hooks**: Customize request/response workflows for logging, metrics, and more
- **Comprehensive Docs**: Access usage examples for every endpoint with copy-pastable code samples

### Security Improvements

All Speakeasy-generated PHP SDKs follow industry best practices for security, including:

- **Ephemeral Token Storage**: Prevent persistence of sensitive credentials
- **HTTPS-Only Connections**: Proper certificate validation for all requests
- **Custom Security Policies**: Configurable security middleware for your needs
- **Secure Error Handling**: Prevents sensitive information leakage

### Performance Improvements

Performance is equally critical, especially for high-throughput applications:

- **Minimal Dependencies**: We use only what's necessary to keep your dependency tree lean
- **Connection Pooling**: Reuse HTTP connections for better performance under load
- **Lazy Loading**: Resources are only initialized when accessed to reduce memory footprint
- **PSR-18 HTTP Client**: Compatible with any PSR-18 client for maximum flexibility
- **Request Batching**: Group multiple API calls into a single HTTP request where supported

These optimizations ensure that your API integrations remain fast and reliable, even at scale.

---

## Core SDK Features In-Depth

### Type Safety

PHP's journey from a loosely typed language to one embracing strong typing has been remarkable. Our SDK Generator maximizes PHP 8's type system to create truly type-safe SDKs that reduce runtime errors and improve developer productivity.

Here's how our type-safe approach translates into real code:

```php
class Payment
{
    public string $id;
    public float $amount;
    public Currency $currency;
    public Status $status;
    public \DateTime $createdAt;
    public ?string $description;
    public Customer|Organization $owner;

    public function __construct(
        string $id,
        float $amount,
        Currency $currency,
        Status $status,
        \DateTime $createdAt,
        ?string $description,
        Customer|Organization $owner
    ) {
        $this->id = $id;
        $this->amount = $amount;
        $this->currency = $currency;
        $this->status = $status;
        $this->createdAt = $createdAt;
        $this->description = $description;
        $this->owner = $owner;
    }
}
```

This approach ensures that your IDE can provide accurate auto-completion, type-related errors are caught early, and developers can build with confidence.

We go even further by leveraging docstrings to provide additional type information, particularly for typed collections – something that PHP's built-in type system doesn't yet support natively:

```php
/**
 * Process payments with enhanced type safety
 * 
 * @param array<Transaction> $transactions List of transactions to process
 * @param ?PaymentProvider $provider Optional payment provider
 * @return array<Receipt>|ErrorResponse Collection of receipts or error response
 */
function processPayments(
    array $transactions, 
    ?PaymentProvider $provider = null
): array|ErrorResponse 
{
    // Enhanced type-safe operations with IDE support for collection types
    // Your IDE now knows $transactions contains only Transaction objects
    // and the return value is either an array of Receipt objects or an ErrorResponse
}
```

With these enhanced type annotations, IDEs can provide even more precise code completion and type checking than PHP's native type system alone allows.

### BigInt and Decimal Support

Financial applications demand precision, and PHP's floating-point limitations often cause problems when handling currency values or large IDs. Our PHP SDKs solve this with native BigInt and Decimal support that maintains precision throughout the entire request/response lifecycle:

```php
// Problem with regular floats/integers
$regularFloat = 0.1 + 0.2;
echo $regularFloat;  // Outputs: 0.30000000000000004 (precision error)

// With our Decimal support
use YourAPI\Types\Decimal;
$preciseDecimal = new Decimal('0.1')->add(new Decimal('0.2'));
echo $preciseDecimal;  // Outputs: 0.3 (exact precision)

// Creating a transaction with precise decimal amounts
$transaction = $client->transactions->create([
    'amount' => new Decimal('1234.56789012345'),
    'accountId' => new BigInt('9007199254740991'),
    'exchangeRate' => new Decimal('1.2345678901234567890')
]);

// Performing precise calculations with returned values
$fee = $transaction->amount->multiply(new Decimal('0.029'));
$netAmount = $transaction->amount->subtract($fee);

echo "Transaction Amount: {$transaction->amount}\n";
echo "Fee (2.9%): {$fee}\n";
echo "Net Amount: {$netAmount}\n";
```

Our implementation preserves precision at every step in the data journey, from API request to business logic processing to storage — critical for financial services, blockchain applications, and scientific computing.

### OAuth 2.0

Implementing OAuth flows correctly can be challenging. Our PHP SDKs now include built-in support for OAuth 2.0, making secure API integration straightforward:

```php
// Initialize client with OAuth credentials
$client = Client::builder()
    ->setSecurity(new Security(
        $clientId = 'your-client-id', 
        $clientSecret = 'your-client-secret'
    ))
    ->build();

// Generate authorization URL - redirect URL is configured at the provider level
$authUrl = $client->auth()->getAuthorizationUrl([
    'scopes' => ['read', 'write'],
    'state' => $csrf_token
]);

// Redirect user to $authUrl

// In your callback handler:
$tokens = $client->auth()->exchangeCode($code);

// The client will automatically use and refresh tokens for future requests
$response = $client->resources->list();
```

---

## Laravel Integration

PHP developers choose frameworks to increase productivity, with Laravel being the most popular choice. Our GA release includes first-class Laravel support with dependency injection, comprehensive testing utilities, and middleware compatibility.

### Simple Installation Via Composer

```bash
composer require your-api/laravel-sdk
```

### Automatic Service Provider Registration

```php
// In config/app.php
'providers' => [
    // Other Service Providers...
    YourAPI\Laravel\YourAPIServiceProvider::class,
],

// In .env
YOUR_API_KEY=sk_test_123456789
YOUR_API_ENVIRONMENT=sandbox
```

### Dependency Injection In Controllers

```php
use YourAPI\Client;
use YourAPI\Resources\Payment;
use YourAPI\Exceptions\ApiException;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    public function __construct(
        private Client $client,  // Auto-injected from the service container
    ) {}
    
    public function processPayment(Request $request)
    {
        try {
            $payment = $this->client->payments->create([
                'amount' => $request->input('amount'),
                'currency' => Currency::USD,
                'description' => $request->input('description'),
                'metadata' => [
                    'order_id' => $request->input('order_id'),
                    'customer_id' => auth()->id(),
                ],
            ]);
            
            // Store payment reference in your database
            $order = Order::find($request->input('order_id'));
            $order->payment_id = $payment->id;
            $order->payment_status = $payment->status;
            $order->save();
            
            return view('payment.confirmation', ['payment' => $payment]);
        } catch (ApiException $e) {
            // Comprehensive error handling with specific error types
            return back()->withErrors([
                'payment' => $e->getMessage(),
                'error_code' => $e->getErrorCode(),
                'error_type' => $e->getErrorType(),
            ]);
        }
    }
}
```

---

## Real-World Integration Example

To illustrate how these features work together, here's a simplified example of a subscription management system:

```php
<?php

namespace App\Services;

use App\Models\Customer;
use App\Models\Subscription;
use YourAPI\Client;
use YourAPI\Types\Decimal;
use YourAPI\Exceptions\ApiException;

class SubscriptionService
{
    private Client $client;
    
    public function __construct(Client $client)
    {
        $this->client = $client;
        
        // Register telemetry hooks for observability
        $this->client->registerHook(new YourAPI\Hooks\BeforeRequestHook());
        $this->client->registerHook(new YourAPI\Hooks\AfterResponseHook());
    }
    
    /**
     * Create a new subscription for a customer
     */
    public function createSubscription(Customer $customer, string $planId): Subscription
    {
        try {
            // Create the subscription with typed parameters
            $paymentSubscription = $this->client->subscriptions->create([
                'customer' => $customer->payment_customer_id,
                'plan' => $planId,
                'billing_cycle_anchor' => new \DateTime('first day of next month'),
                'proration_behavior' => 'none',
            ]);
            
            // Persist subscription details to local database
            $subscription = new Subscription([
                'customer_id' => $customer->id,
                'payment_subscription_id' => $paymentSubscription->id,
                'status' => $paymentSubscription->status,
            ]);
            
            $subscription->save();
            return $subscription;
            
        } catch (ApiException $e) {
            // Type-safe error handling with specific exception types
            throw new PaymentFailedException($e->getUserFacingMessage());
        }
    }
    
    /**
     * Process transactions for reconciliation with auto-pagination
     */
    public function reconcileTransactions(\DateTime $startDate, \DateTime $endDate): array
    {
        $summary = [
            'total' => 0,
            'successful' => 0,
            'total_amount' => new Decimal('0'),
        ];
        
        // SDK handles pagination automatically
        $transactions = $this->client->transactions->list([
            'created' => [
                'gte' => $startDate->format('Y-m-d'),
                'lte' => $endDate->format('Y-m-d'),
            ],
        ]);
        
        // Auto-paginating iterator
        foreach ($transactions as $transaction) {
            $summary['total']++;
            
            if ($transaction->status === 'succeeded') {
                $summary['successful']++;
                $summary['total_amount'] = $summary['total_amount']->add($transaction->amount);
            }
        }
        
        return $summary;
    }
}
```

This example demonstrates the key features of our SDK in a production context, showing how type safety, pagination, and decimal handling work together seamlessly.

---

## Get Started Today

Ready to deliver a world-class developer experience to your PHP users? Here's how to get started:

1. [Generate your PHP SDK in less than 5 minutes](/docs/sdks/create-client-sdks)
2. [Read the documentation for configuration options](/docs/languages/php/methodology-php)

PHP 8 has evolved into a powerful, type-safe language, and with our SDK generator, you can now provide your users with a developer experience that leverages all these capabilities. Try it out and see how it can simplify your API integration workflow.