
PHP Example
Our documentation presents implementation examples of the WaveLight API using PHP, a robust and widely used language in web development. The following examples demonstrate how to efficiently and securely integrate our API into PHP projects.
We designed these guides for developers who prefer working with PHP, offering practical and direct implementations of the main WaveLight API features. Our examples cover everything from basic settings to more complex integration scenarios.
Explore the codes and tutorials to learn how to perform file uploads, process real-time events, and manage asynchronous requests using PHP.
Service Request - Usage Example
This PHP implementation provides a robust solution for creating medical service requests through the Wavelight Health API. The code is designed to be flexible, secure, and easy to integrate into healthcare management systems.
Main Structure
Service and Gender Enumerations
class Service {
public const HEART_BEATS = "HEART BEATS";
public const BLOOD_PRESSURE = "BLOOD PRESSURE";
public const OXIMETRY = "OXIMETRY";
}
class Gender {
public const UNDEFINED = "UNDEFINED";
public const MALE = "MALE";
public const FEMALE = "FEMALE";
}
Purpose:
-
Defines constants for available medical services
-
Provides a standardized way to reference services and genders
-
Enhances code maintenance and readability
Patient Data Interface
interface WorkflowPerson {
public function getHeight(): float;
public function getWeight(): float;
public function getAge(): int;
public function getGender(): string;
}
Characteristics:
-
Defines a contract for classes representing patient data
-
Ensures all implementations provide methods to retrieve basic information
-
Allows flexibility in creating different patient data objects
Patient Data Implementation
class PatientData implements WorkflowPerson {
private float $height;
private float $weight;
private int $age;
private string $gender;
public function __construct(float $height, float $weight, int $age, string $gender) {
$this->height = $height;
$this->weight = $weight;
$this->age = $age;
$this->gender = $gender;
}
// Getter methods implemented...
}
Benefits:
-
Secure encapsulation of patient data
-
Simple attribute validation and manipulation
-
Easy creation of patient objects
Main Service Request Function
function createServiceRequestRequest(array $selectedServices, WorkflowPerson $person): ServiceRequestResponse {
$apiKey = getenv('API_KEY');
$payload = [
'serviceList' => $selectedServices,
'WPG_Object' => [
// Detailed payload structure...
],
];
// cURL request configuration and sending
$ch = curl_init('https://api.wavelighthealth.com/api');
// cURL settings...
$response = curl_exec($ch);
// Error handling and response processing
}
Key Functionalities:
-
Dynamic request payload assembly
-
Secure API key utilization
-
Flexible service selection
-
Robust communication error handling
Usage Example
try {
$person = new PatientData(175.5, 70.0, 30, Gender::MALE);
$services = [Service::HEART_BEATS, Service::BLOOD_PRESSURE];
$result = createServiceRequestRequest($services, $person);
echo "Request ID: " . $result->requestId;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Demonstration:
-
Simple patient object creation
-
Multiple service selection
-
Exception handling
Security Considerations
-
Environment variable usage for API key storage
Input data validation and sanitization
Error handling with exceptions
Requirements
-
PHP 7.4 or higher
cURL extension enabled
API key environment variable configuration
Performance Optimization
-
Minimal object creation
-
Efficient data processing
-
Lightweight payload structure
Potential Improvements
-
Implement additional data validation
-
Add request logging mechanism
-
Create retry mechanism for communication failures
-
Implement more comprehensive error handling
Troubleshooting
-
Ensure API key is correctly set
-
Verify network connectivity
-
Check PHP and cURL configuration
-
Validate input data types and formats
File Upload Function
The FileUploader class provides robust methods for file uploads using pre-signed URLs, supporting different file input methods.
Main Methods
uploadFileOn
public static function uploadFileOn(
ServiceRequestResponse $presigned,
string $filePath
): array
Parameters:
-
$presigned : Object with pre-signed upload URL
-
$filePath : Full path of the file to be uploaded
Features:
-
Upload via file system path
-
Binary file support
-
Comprehensive error handling
uploadFileFromStream()
public static function uploadFileFromStream(
ServiceRequestResponse $presigned,
$fileResource
): array
Parameters:
-
$presigned : Object with pre-signed upload URL
-
$fileResource : File stream resource
Features:
-
Upload from stream resources
-
Input flexibility
-
Resource validation
Usage Example
try {
$serviceResponse = new ServiceRequestResponse();
$serviceResponse->uploadVideoUrl = 'https://example.com/upload';
// File upload
$uploadResult = FileUploader::uploadFileOn(
$serviceResponse,
'/path/to/file.mp4'
);
// Stream upload
$fileStream = fopen('/path/to/file.mp4', 'r');
$streamResult = FileUploader::uploadFileFromStream(
$serviceResponse,
$fileStream
);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Error Handling:
-
Exceptions for scenarios such as:
-
File not found
-
Reading failure
-
Network errors
-
Invalid HTTP status codes
-
Upload Configuration:
-
HTTP Method: PUT
-
Content Type: application/octet-stream
-
Binary upload support
Server-Sent Events (SSE)
This implementation provides a robust method for handling Server-Sent Events (SSE) in PHP, specifically designed for tracking service request results in real-time from the Wavelight Health Gateway.
Function Signature
listenToServiceResults
function listenToServiceResults($requestId, $selectedServices, $onResultsCallback)
Parameters:
-
$requestId : A unique identifier for the service request
-
$selectedServices : An array of services to track
-
$onResultsCallback : A callback function to process incoming results
Key Implementation Details
1. Authentication and Headers Setup
$apiKey = getenv('API_KEY');
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
];
Purpose:
-
Retrieves the API key from environment variables
-
Prepares authentication headers for the SSE connection
-
Uses Bearer token authentication
2. Stream Context Creation
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => implode("\r\n", $headers)
]
]);
Purpose:
-
Creates a stream context with custom HTTP headers
-
Allows setting up GET request with authentication
-
Enables connection to SSE endpoint with proper credentials
3. Event Processing Logic
while (!feof($stream)) {
$line = fgets($stream);
if (strpos($line, 'data:') === 0) {
try {
$eventData = json_decode(trim(substr($line, 5)), true);
if (!empty($eventData['results'])) {
$parsedResults = array_map(function($result) {
$result['return'] = json_decode($result['return'], true);
return $result;
}, $eventData['results']);
$onResultsCallback($parsedResults);
$allServicesReturned = array_reduce($selectedServices, function($carry, $service) use ($parsedResults) {
return $carry && array_filter($parsedResults, function($result) use ($service) {
return $result['name'] === $service;
});
}, true);
if ($allServicesReturned) {
fclose($stream);
break;
}
}
} catch (Exception $error) {
error_log("[SSE] Failed to process message: " . $error->getMessage());
}
}
}
Key Processing Steps:
-
Read stream line by line
-
Identify event data lines (starting with 'data:')
-
Decode JSON event data
-
Transform results by parsing nested JSON
-
Invoke callback with parsed results
-
Check if all selected services have returned
-
Close connection when all services complete
-
Log any processing errors
4. Service Completion Check
$allServicesReturned = array_reduce($selectedServices, function($carry, $service) use ($parsedResults) {
return $carry && array_filter($parsedResults, function($result) use ($service) {
return $result['name'] === $service;
});
}, true);
Purpose:
-
Uses array_reduce() to check if all selected services have returned results
-
Provides a mechanism to automatically close the SSE connection
Error Handling:
-
Uses error_log() for logging connection and processing errors
-
Gracefully handles potential JSON decoding failures
-
Prevents script termination on individual event processing errors
Usage Example
$requestId = 'example-request-id';
$selectedServices = ['service1', 'service2'];
listenToServiceResults($requestId, $selectedServices, function($results) {
// Process received results
print_r($results);
});
Considerations:
-
Requires PHP with stream and JSON support
-
Best used in long-running PHP processes
-
Suitable for CLI or background job environments
Potential Improvements:
-
Add timeout mechanism
-
Implement reconnection strategy
-
Add more detailed logging
-
Support for custom error handling
This documentation serves as a quick guide to integrating with the Wavelight Health API. For more information, see the official documentation.