### Run Quick Start Example Source: https://github.com/evansims/openfga-php/blob/main/examples/README.md Execute the 'Quick Start' example to demonstrate essential steps for getting started with OpenFGA using the PHP SDK. Ensure OpenFGA is running. ```bash php quick-start/example.php ``` -------------------------------- ### Setup for Concurrency Examples Source: https://github.com/evansims/openfga-php/blob/main/docs/Features/Concurrency.md This snippet provides the necessary setup for running concurrency examples, including client initialization and store/model IDs. Ensure this is executed before other concurrency examples. ```php use OpenFGA\OpenFGAClient; use OpenFGA\Models\AuthorizationModel; use OpenFGA\Models\TupleKey; // Assume $client is an initialized OpenFGAClient instance // Assume $storeId and $modelId are valid store and model identifiers $tuplesToWrite = [ tuple('user:alice', 'member', 'group:admins'), tuple('user:bob', 'member', 'group:users'), tuple('user:charlie', 'member', 'group:users'), ]; $tuplesToDelete = [ new TupleKey('user:alice', 'member', 'group:admins'), ]; $model = new AuthorizationModel( typeDefinitions: [ // ... your type definitions ... ] ); ``` -------------------------------- ### Install OpenFGA PHP SDK and Dependencies Source: https://context7.com/evansims/openfga-php/llms.txt Install the SDK using Composer and add necessary PSR HTTP implementations. Includes an example for starting a local OpenFGA server. ```bash # Install the SDK composer require evansims/openfga-php # Add PSR HTTP implementations (Guzzle example) composer require guzzlehttp/guzzle guzzlehttp/psr7 # Or lightweight alternative composer require nyholm/psr7 php-http/curl-client # Start a local OpenFGA server docker run -d -p 8080:8080 --name openfga openfga/openfga run ``` -------------------------------- ### OpenFGA PHP SDK Setup Source: https://github.com/evansims/openfga-php/blob/main/docs/Essentials/Stores.md Initializes the OpenFGA client with the necessary configuration. Ensure the SDK is installed via Composer. ```php 'http://localhost:8080', 'store_api_port' => 8080, 'store_api_scheme' => 'http', ]); ``` -------------------------------- ### Setup OpenFGA Client Source: https://github.com/evansims/openfga-php/blob/main/docs/Essentials/Models.md Initializes the OpenFGA client with necessary configuration. Ensure the SDK is installed and configured with your OpenFGA server details. ```php require __DIR__ . "/../../vendor/autoload.php"; use OpenFGA\SDK\OpenFGA; $client = OpenFGA::factory([ "store_id" => "your-store-id", "api_url" => "http://localhost:8080", ]); ``` -------------------------------- ### Setup for Assertions Source: https://github.com/evansims/openfga-php/blob/main/docs/Essentials/Assertions.md This snippet shows the necessary setup for working with assertions in your PHP project. Ensure you have the OpenFGA client and any required dependencies installed. ```php writeAuthorizationModel($model); $client->writeAssertions($assertions); ``` -------------------------------- ### Setup OpenFGA Client Source: https://github.com/evansims/openfga-php/blob/main/docs/Essentials/Queries.md Initializes the OpenFGA client with necessary configuration. This setup is a prerequisite for all query operations. ```php '01HXXXXXXXXXXXXXX1', 'api_url' => 'http://localhost:8080', 'credentials' => [ 'client_id' => 'your_client_id', 'client_secret' => 'your_client_secret', ], ]); // Use the client for queries... ?> ``` -------------------------------- ### Install Composer Dependencies Source: https://github.com/evansims/openfga-php/blob/main/examples/README.md Install the necessary Composer dependencies for the OpenFGA PHP SDK. This is a prerequisite for running the examples. ```bash composer install ``` -------------------------------- ### Run Hello World Example Source: https://github.com/evansims/openfga-php/blob/main/examples/README.md Execute the 'Hello World' example to see the simplest introduction to OpenFGA in PHP. Ensure OpenFGA is running. ```bash php hello-world/example.php ``` -------------------------------- ### Setup for Tuple Operations Source: https://github.com/evansims/openfga-php/blob/main/docs/Essentials/Tuples.md This snippet shows the necessary setup for performing tuple operations. Ensure you have the OpenFGA SDK initialized. ```php 'your-store-id', 'api_url' => 'http://localhost:8080', ]); $user = 'user:anne'; $resource = 'document:technical-specs'; $relation = 'editor'; ``` -------------------------------- ### Complete Event-Driven Telemetry Example in PHP Source: https://github.com/evansims/openfga-php/wiki/Observability This snippet demonstrates a full event-driven telemetry setup. It includes registering custom logging and metrics listeners with an EventDispatcher, initializing the OpenFGA client with the dispatcher, performing several OpenFGA operations (store, model, write, allowed), and finally printing the collected metrics. Ensure custom listener classes and event classes are defined elsewhere. ```php // Your custom listeners (defined above) $eventDispatcher = new EventDispatcher(); $loggingListener = new LoggingEventListener(); $metricsListener = new MetricsEventListener(); // Register all listeners $eventDispatcher->addListener(HttpRequestSentEvent::class, [$loggingListener, 'onHttpRequestSent']); $eventDispatcher->addListener(HttpResponseReceivedEvent::class, [$loggingListener, 'onHttpResponseReceived']); $eventDispatcher->addListener(OperationStartedEvent::class, [$loggingListener, 'onOperationStarted']); $eventDispatcher->addListener(OperationCompletedEvent::class, [$loggingListener, 'onOperationCompleted']); $eventDispatcher->addListener(OperationStartedEvent::class, [$metricsListener, 'onOperationStarted']); $eventDispatcher->addListener(OperationCompletedEvent::class, [$metricsListener, 'onOperationCompleted']); $client = new Client( url: $apiUrl, eventDispatcher: $eventDispatcher, ); // Perform operations - events will be triggered automatically $storeId = store($client, 'telemetry-demo'); $authModel = dsl($client, ' model schema 1.1 type user type document relations define viewer: [user] '); $modelId = model($client, $storeId, $authModel); write($client, $storeId, $modelId, tuple('user:alice', 'viewer', 'document:report')); $canView = allowed($client, $storeId, $modelId, tuple('user:alice', 'viewer', 'document:report')); // View collected metrics echo "Collected Metrics:\n"; print_r($metricsListener->getMetrics()); ``` -------------------------------- ### Run Observability Example Source: https://github.com/evansims/openfga-php/blob/main/examples/README.md Execute the 'Observability' example to demonstrate OpenTelemetry integration for production monitoring and tracing. Ensure OpenFGA is running. ```bash php observability/example.php ``` -------------------------------- ### Install with Verbose Output Source: https://github.com/evansims/openfga-php/wiki/Installation When installing the OpenFGA PHP package, use the -vvv flag for verbose output to get detailed information that can help pinpoint installation errors. ```bash composer require evansims/openfga-php -vvv ``` -------------------------------- ### Run Event-Driven Telemetry Example Source: https://github.com/evansims/openfga-php/blob/main/examples/README.md Execute the 'Event-Driven Telemetry' example to demonstrate custom event listeners for observability without tight coupling. Ensure OpenFGA is running. ```bash php event-driven-telemetry/example.php ``` -------------------------------- ### Create Metrics Event Listener Source: https://github.com/evansims/openfga-php/wiki/Observability Implement a listener to collect metrics such as operation counts and durations. This example tracks the start time of operations and calculates their duration upon completion. ```php final class MetricsEventListener { private array $operationTimes = []; private array $requestCounts = []; public function onOperationStarted(OperationStartedEvent $event): void { $this->operationTimes[$event->getEventId()] = microtime(true); } public function onOperationCompleted(OperationCompletedEvent $event): void { $operation = $event->getOperation(); // Count operations $this->requestCounts[$operation] = ($this->requestCounts[$operation] ?? 0) + 1; // Track timing if (isset($this->operationTimes[$event->getEventId()])) { $duration = microtime(true) - $this->operationTimes[$event->getEventId()]; echo "[{$operation}] completed in " . round($duration * 1000, 2) . "ms "; unset($this->operationTimes[$event->getEventId()]); } } public function getMetrics(): array { return [ 'request_counts' => $this->requestCounts, 'active_operations' => count($this->operationTimes), ]; } } ``` -------------------------------- ### Development Installation with Git and Composer Source: https://github.com/evansims/openfga-php/wiki/Installation Clone the repository and use Composer to install dependencies and run tests for development purposes. ```bash git clone https://github.com/evansims/openfga-php.git cd openfga-php composer install composer test ``` -------------------------------- ### Run Duplicate Filtering Example Source: https://github.com/evansims/openfga-php/blob/main/examples/README.md Execute the 'Duplicate Filtering' example to demonstrate automatic tuple filtering and delete precedence. Ensure OpenFGA is running. ```bash php duplicate-filtering/example.php ``` -------------------------------- ### Start OpenFGA Server with Docker Source: https://github.com/evansims/openfga-php/wiki/Introduction Use this command to quickly start a local OpenFGA server instance using Docker. The server will be accessible at http://localhost:8080. ```bash docker run -d -p 8080:8080 --name openfga openfga/openfga run ``` -------------------------------- ### Create Logging Event Listener Source: https://github.com/evansims/openfga-php/wiki/Observability Implement a listener to log HTTP request and response details, as well as operation start and completion events. This example demonstrates how to access event data to log relevant information. ```php final class LoggingEventListener { public function onHttpRequestSent(HttpRequestSentEvent $event): void { echo "[{$event->getOperation()}] HTTP Request: {$event->getRequest()->getMethod()} {$event->getRequest()->getUri()} "; } public function onHttpResponseReceived(HttpResponseReceivedEvent $event): void { $status = $event->getResponse() ? $event->getResponse()->getStatusCode() : 'N/A'; $success = $event->isSuccessful() ? '✅' : '❌'; echo "[{$event->getOperation()}] HTTP Response: {$success} {$status} "; } public function onOperationStarted(OperationStartedEvent $event): void { echo "[{$event->getOperation()}] Started - Store: {$event->getStoreId()} "; } public function onOperationCompleted(OperationCompletedEvent $event): void { $success = $event->isSuccessful() ? '✅' : '❌'; echo "[{$event->getOperation()}] Completed: {$success} "; } } ``` -------------------------------- ### Run Non-Transactional Writes Example Source: https://github.com/evansims/openfga-php/blob/main/examples/README.md Execute the 'Non-Transactional Writes' example to show Fiber-based parallel batch processing for high-performance operations. Ensure OpenFGA is running. ```bash php non-transactional-writes/example.php ``` -------------------------------- ### Install OpenFGA PHP SDK with Composer Source: https://github.com/evansims/openfga-php/blob/main/README.md Use Composer to install the OpenFGA PHP SDK. This command should be run in your project's root directory. ```bash composer require evansims/openfga-php ``` -------------------------------- ### Example: Find Users and Groups with Access Source: https://github.com/evansims/openfga-php/wiki/API-ClientInterface Shows how to find both direct users and groups that have a specified relationship with an object. This example filters for both 'user' and 'group' types. ```php $userFilters = new UserTypeFilters([ new UserTypeFilter('user'), new UserTypeFilter('group') ]); $result = $client->listUsers( store: 'store-id', model: 'model-id', object: 'document:sensitive', relation: 'editor', userFilters: $userFilters ); / ``` -------------------------------- ### Production Composer Installation Source: https://github.com/evansims/openfga-php/wiki/Installation Install production dependencies and optimize the autoloader using Composer's --no-dev flag. ```bash composer install --no-dev --optimize-autoloader ``` -------------------------------- ### Install OpenTelemetry PHP Packages Source: https://github.com/evansims/openfga-php/wiki/Observability Install the necessary OpenTelemetry packages using Composer. This is recommended for full observability functionality with the OpenFGA PHP SDK. ```bash composer require open-telemetry/api open-telemetry/sdk ``` -------------------------------- ### Use Existing OpenTelemetry Setup Source: https://github.com/evansims/openfga-php/wiki/Observability When an OpenTelemetry SDK is already configured globally, the OpenFGA SDK will automatically leverage that existing setup for telemetry. No explicit configuration of the telemetry provider is needed in this case. ```php // The SDK will automatically use your existing global configuration $telemetry = TelemetryFactory::create('my-authorization-service'); $client = new Client( url: $apiUrl, telemetry: $telemetry ); // Traces will be included in your existing observability setup ``` -------------------------------- ### Prerequisites and Client Setup Source: https://github.com/evansims/openfga-php/blob/main/docs/Features/Results.md Sets up the necessary imports and initializes the OpenFGA client with a URL and retrieves store and model IDs. Assumes environment variables are set for store and model IDs. ```php use OpenFGA\Client; use OpenFGA\Models\Store; use OpenFGA\Models\AuthorizationModel; use OpenFGA\Exceptions\ClientError; use OpenFGA\Exceptions\ClientException; use OpenFGA\Exceptions\NetworkError; use OpenFGA\Exceptions\NetworkException; use function OpenFGA\result; use function OpenFGA\ok; use function OpenFGA\err; use function OpenFGA\unwrap; use function OpenFGA\success; use function OpenFGA\failure; use function OpenFGA\tuple; use function OpenFGA\allowed; $client = new Client(url: 'http://localhost:8080'); $storeId = $_ENV['FGA_STORE_ID'] ?? 'your-store-id'; $modelId = $_ENV['FGA_MODEL_ID'] ?? 'your-model-id'; $store = $client->getStore($storeId)->unwrap(); $model = $client->getAuthorizationModel($storeId, $modelId)->unwrap(); ``` -------------------------------- ### Get Default Message Key for Configuration Error Source: https://github.com/evansims/openfga-php/wiki/API-Exceptions-DefaultMessages Retrieves the default message key for a configuration error. Use this to guide users on resolving setup issues, such as missing PSR components or incorrect SDK configuration. ```php public function forConfigurationError(ConfigurationError $error): Messages ``` -------------------------------- ### Start OpenFGA Operation Tracing Source: https://github.com/evansims/openfga-php/wiki/API-Observability-TelemetryInterface Starts tracing a high-level OpenFGA API operation by creating a new trace span. Includes relevant attributes like store ID and model ID. ```php public function startOperation( string $operation, StoreInterface|string $store, AuthorizationModelInterface|string|null $model = NULL, array $attributes = [], ): object|null ``` -------------------------------- ### OpenFGA Operation Span Example Source: https://github.com/evansims/openfga-php/wiki/Observability This example shows the typical attributes logged for an OpenFGA operation span, including operation type, store ID, model ID, and SDK details. ```text openfga.operation: check openfga.store_id: store_01H1234567890ABCDEF openfga.model_id: model_01H1234567890ABCDEF openfga.sdk.name: openfga-php openfga.sdk.version: 1.0.0 ``` -------------------------------- ### Install Lightweight PSR Dependencies with Nyholm Source: https://github.com/evansims/openfga-php/wiki/Installation Install Nyholm's PSR7 implementation and a curl-based HTTP client for a more lightweight PSR dependency setup. ```bash composer require nyholm/psr7 php-http/curl-client ``` -------------------------------- ### Get Operation from HttpResponseReceivedEvent Source: https://github.com/evansims/openfga-php/wiki/API-Events-HttpResponseReceivedEvent Retrieve the name of the OpenFGA operation that was performed. Examples include 'check', 'write', or 'read'. ```php public function getOperation(): string { // ... implementation details } ``` -------------------------------- ### Initialize OpenFGA Client Source: https://github.com/evansims/openfga-php/wiki/Assertions Set up the OpenFGA client with the API URL and store/model IDs. Ensure environment variables are set or provide default values. ```php isAdmin() || $user->owns($document) || $user->team->canEdit($document)) { // ... } // Ask OpenFGA: $canEdit = allowed( client: $client, store: 'my-store', model: 'my-model', tuple: tuple('user:alice', 'editor', 'document:readme') ); // Zero business logic coupling. Pure authorization. ``` -------------------------------- ### Get Locale Code Source: https://github.com/evansims/openfga-php/wiki/API-Language Retrieves the full locale code for the language, including any region specifier. For example, 'pt_BR' for Brazilian Portuguese. ```php public function locale(): string ``` -------------------------------- ### getWrapperKey() Source: https://github.com/evansims/openfga-php/wiki/API-Schemas-CollectionSchema Get the wrapper key for the collection data if any. Some collections expect data wrapped in a specific key (for example, Usersets uses 'child'). ```APIDOC ## getWrapperKey() ### Description Get the wrapper key for the collection data if any. Some collections expect data wrapped in a specific key (for example, Usersets uses 'child'). ### Returns `string` | `null` — The wrapper key or null if data is not wrapped ``` -------------------------------- ### Get Start Time - PHP Source: https://github.com/evansims/openfga-php/blob/main/docs/API/Requests/ListTupleChangesRequest.md Retrieves the earliest timestamp to include in the change history. Use this to filter changes within a specific time range. ```php public function getStartTime(): ?DateTimeImmutable ``` -------------------------------- ### Prerequisites for OpenFGA PHP SDK Examples Source: https://github.com/evansims/openfga-php/wiki/Results Sets up the necessary imports and client initialization for using the OpenFGA PHP SDK. Ensure the FGA_STORE_ID and FGA_MODEL_ID environment variables are set. ```php use OpenFGA\{Client, ClientInterface}; use OpenFGA\Models\{Store, AuthorizationModel}; use OpenFGA\Exceptions\{ClientError, ClientException, NetworkError, NetworkException}; use function OpenFGA\{result, ok, err, unwrap, success, failure, tuple, allowed}; $client = new Client(url: 'http://localhost:8080'); $storeId = $_ENV['FGA_STORE_ID'] ?? 'your-store-id'; $modelId = $_ENV['FGA_MODEL_ID'] ?? 'your-model-id'; $store = $client->getStore($storeId)->unwrap(); $model = $client->getAuthorizationModel($storeId, $modelId)->unwrap(); ``` -------------------------------- ### Initialize OpenFGA PHP Client Source: https://github.com/evansims/openfga-php/wiki/Integration Sets up the OpenFGA client with environment variables for API URL and authentication credentials. Ensure all required environment variables are configured. ```php use OpenFGA\{Client, ClientInterface}; use OpenFGA\Authentication\ClientCredentialAuthentication; use function OpenFGA\{tuple, tuples, allowed, write, delete}; $client = new Client( url: $_ENV['FGA_API_URL'], authentication: new ClientCredentialAuthentication( clientId: $_ENV['FGA_CLIENT_ID'], clientSecret: $_ENV['FGA_CLIENT_SECRET'], issuer: $_ENV['FGA_ISSUER'], audience: $_ENV['FGA_AUDIENCE'], ), ); $storeId = $_ENV['FGA_STORE_ID']; $modelId = $_ENV['FGA_MODEL_ID']; ``` -------------------------------- ### getType() Source: https://github.com/evansims/openfga-php/wiki/API-Models-UsersetUserInterface Get the object type in the userset reference. This represents the type of object that the userset refers to. For example, in "group:eng#member," this would return "group." ```APIDOC ## getType ### Description Get the object type in the userset reference. This represents the type of object that the userset refers to. For example, in "group:eng#member," this would return "group." ### Method ```php public function getType(): string ``` ### Returns `string` — The object type ``` -------------------------------- ### Configure OpenTelemetry and Initialize OpenFGA Client Source: https://github.com/evansims/openfga-php/wiki/Observability Sets up a basic OpenTelemetry tracer provider with a SimpleSpanProcessor and OTLP exporter. It then registers the tracer provider and creates an OpenFGA client with telemetry enabled. ```php // Configure OpenTelemetry (this is a basic example) $tracerProvider = new TracerProvider([ new SimpleSpanProcessor( new SpanExporter($_ENV['OTEL_EXPORTER_OTLP_ENDPOINT'] ?? 'http://localhost:4317') ) ]); Globals::registerInitializer(function () use ($tracerProvider) { return \OpenTelemetry\SDK\Registry::get()->tracerProvider($tracerProvider); }); // Create telemetry with your service information $telemetry = TelemetryFactory::create( serviceName: 'my-authorization-service', serviceVersion: '1.2.3' ); // Configure client $client = new Client( url: $apiUrl, telemetry: $telemetry ); // Operations are now traced and exported to your backend $result = $client->listObjects( store: $storeId, model: $modelId, user: 'user:anne', relation: 'viewer', type: 'document' ); ``` -------------------------------- ### PHP Event-Driven Telemetry Example Source: https://github.com/evansims/openfga-php/blob/main/docs/Features/Observability.md This example demonstrates setting up custom listeners for logging and metrics, registering them with an EventDispatcher, and then performing OpenFGA operations. Events like HTTP requests, responses, and operation start/completion will trigger the registered listeners. ```php // Your custom listeners (defined above) $eventDispatcher = new EventDispatcher(); $loggingListener = new LoggingEventListener(); $metricsListener = new MetricsEventListener(); // Register all listeners $eventDispatcher->addListener(HttpRequestSentEvent::class, [$loggingListener, 'onHttpRequestSent']); $eventDispatcher->addListener(HttpResponseReceivedEvent::class, [$loggingListener, 'onHttpResponseReceived']); $eventDispatcher->addListener(OperationStartedEvent::class, [$loggingListener, 'onOperationStarted']); $eventDispatcher->addListener(OperationCompletedEvent::class, [$loggingListener, 'onOperationCompleted']); $eventDispatcher->addListener(OperationStartedEvent::class, [$metricsListener, 'onOperationStarted']); $eventDispatcher->addListener(OperationCompletedEvent::class, [$metricsListener, 'onOperationCompleted']); $client = new Client( url: $apiUrl, eventDispatcher: $eventDispatcher, ); // Perform operations - events will be triggered automatically $storeId = store($client, 'telemetry-demo'); $authModel = dsl($client, ' model schema 1.1 type user type document relations define viewer: [user] '); $modelId = model($client, $storeId, $authModel); write($client, $storeId, $modelId, tuple('user:alice', 'viewer', 'document:report')); $canView = allowed($client, $storeId, $modelId, tuple('user:alice', 'viewer', 'document:report')); // View collected metrics echo "Collected Metrics:\n"; print_r($metricsListener->getMetrics()); ``` -------------------------------- ### Security Monitoring with OperationStartedEvent Source: https://github.com/evansims/openfga-php/wiki/Observability Log authorization attempts by listening for the 'check' operation start event. This example demonstrates capturing user IP and agent information for security analysis and SIEM integration. ```php // Note: This is an example helper class and not part of the SDK. final class SecurityEventListener { public function onOperationStarted(OperationStartedEvent $event): void { if ($event->getOperation() === 'check') { // Log authorization attempts for security analysis $this->logSecurityEvent([ 'timestamp' => time(), 'operation' => $event->getOperation(), 'store_id' => $event->getStoreId(), 'user_ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown', 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown', ]); } } private function logSecurityEvent(array $event): void { // Send to security information and event management (SIEM) system $securityLog = json_encode([ 'event_type' => 'authorization_check', 'metadata' => $event, ]); // Log to security monitoring system error_log($securityLog, 3, '/var/log/security/openfga.log'); } } ``` -------------------------------- ### OpenFGA PHP Client Contextual Example Source: https://github.com/evansims/openfga-php/blob/main/CLAUDE.md This example demonstrates the creation of an OpenFGA store and model, writing a tuple to grant permissions, and checking authorization. It uses modern PHP 8.3+ features and domain-relevant names for clarity. ```php use OpenFGA\Client; use function OpenFGA\{dsl, model, store, tuple, write, allowed}; $client = new Client( url: $_ENV['FGA_API_URL'] ?? 'http://localhost:8080' ); $storeId = store( name: 'example-document-system', client: $client ); echo "Created store: {$storeId}\n"; $dsl = <<<'DSL' model schema 1.1 type user type document relations define viewer: [user] define editor: [user] DSL; $model = dsl( dsl: $dsl, client: $client ); $modelId = model( model: $model, store: $storeId, client: $client ); echo "Created model: {$modelId}\n"; write( client: $client, store: $storeId, model: $modelId, tuples: tuple('user:alice', 'viewer', 'document:readme') ); echo "Granted alice viewer permission on readme\n"; $canView = allowed( client: $client, store: $storeId, model: $modelId, tuple: tuple('user:alice', 'viewer', 'document:readme') ); echo $canView ? "✅ Alice can view readme" : "❌ Access denied"; ``` -------------------------------- ### getId() Source: https://github.com/evansims/openfga-php/wiki/API-Models-UsersetUserInterface Get the object identifier in the userset reference. This represents the specific object instance that the userset refers to. For example, in "group:eng#member," this would return "eng." ```APIDOC ## getId ### Description Get the object identifier in the userset reference. This represents the specific object instance that the userset refers to. For example, in "group:eng#member," this would return "eng." ### Method ```php public function getId(): string ``` ### Returns `string` — The object identifier ``` -------------------------------- ### Get Start Time for Change History Source: https://github.com/evansims/openfga-php/wiki/API-Requests-ListTupleChangesRequest Retrieve the earliest time to include in the change history. Only changes that occurred at or after this time will be included, allowing you to focus on recent changes or specific time periods of interest. ```php public function getStartTime(): ?DateTimeImmutable ``` -------------------------------- ### getRelation() Source: https://github.com/evansims/openfga-php/wiki/API-Models-UsersetUserInterface Get the relation name in the userset reference. This represents the specific relation on the referenced object that defines the userset. For example, in "group:eng#member," this would return "member." ```APIDOC ## getRelation ### Description Get the relation name in the userset reference. This represents the specific relation on the referenced object that defines the userset. For example, in "group:eng#member," this would return "member." ### Method ```php public function getRelation(): string ``` ### Returns `string` — The relation name ``` -------------------------------- ### Create and Manage Stores with OpenFGA PHP SDK Source: https://context7.com/evansims/openfga-php/llms.txt Shows how to create a store using a helper function or the direct client method, list all stores with pagination, and delete a store. ```php use OpenFGA\Client; use function OpenFGA\store; $client = new Client(url: 'http://localhost:8080'); // Helper: returns store ID string $storeId = store(name: 'my-app-production', client: $client); echo "Store ID: {$storeId}\n"; // Direct Client method: returns Result $result = $client->createStore(name: 'my-app-staging'); $result ->success(fn($r) => print("Created: {$r->getId()}\n")) ->failure(fn($e) => print("Failed: {$e->getMessage()}\n")); // List all stores with pagination $client->listStores(pageSize: 25) ->success(function ($r) { foreach ($r->getStores() as $s) { echo "{$s->getId()} — {$s->getName()}\n"; } echo "Next token: " . ($r->getContinuationToken() ?? 'none') . "\n"; }); // Delete a store $client->deleteStore($storeId)->unwrap(); ``` -------------------------------- ### getStartTime Source: https://github.com/evansims/openfga-php/blob/main/docs/API/Requests/ListTupleChangesRequestInterface.md Get the start time for filtering changes. Allows specifying a point in time from which to retrieve tuple changes. This is useful for fetching changes that occurred after a specific event or timestamp, enabling focused analysis or synchronization. ```APIDOC ## getStartTime ### Description Get the start time for filtering changes. Allows specifying a point in time from which to retrieve tuple changes. This is useful for fetching changes that occurred after a specific event or timestamp, enabling focused analysis or synchronization. ### Returns `string` | `null` — The start time for filtering changes, or null if not specified ``` -------------------------------- ### Initialize OpenFGA PHP Client Source: https://github.com/evansims/openfga-php/wiki/Models Sets up the OpenFGA client with the API URL and retrieves store and model IDs. Ensure FGA_API_URL and FGA_STORE_ID environment variables are set. ```php getOperation()}] HTTP Request: {$event->getRequest()->getMethod()} {$event->getRequest()->getUri()} "; } public function onHttpResponseReceived(HttpResponseReceivedEvent $event): void { $status = $event->getResponse() ? $event->getResponse()->getStatusCode() : 'N/A'; $success = $event->isSuccessful() ? '✅' : '❌'; echo "[{$event->getOperation()}] HTTP Response: {$success} {$status} "; } public function onOperationStarted(OperationStartedEvent $event): void { echo "[{$event->getOperation()}] Started - Store: {$event->getStoreId()} "; } public function onOperationCompleted(OperationCompletedEvent $event): { $success = $event->isSuccessful() ? '✅' : '❌'; echo "[{$event->getOperation()}] Completed: {$success} "; } } ``` -------------------------------- ### Navigate to Docs Directory Source: https://github.com/evansims/openfga-php/blob/main/tools/docs/README.md Change the current directory to the documentation generation tools. ```bash cd tools/docs ``` -------------------------------- ### Create OpenFGA SDK Client Source: https://github.com/evansims/openfga-php/blob/main/docs/Getting Started/Introduction.md Initialize an SDK Client to interact with your OpenFGA server. Ensure your server is running and accessible. For production, consider adding authentication and error handling. ```php 'http://localhost:8080', ]); ``` -------------------------------- ### getType Source: https://github.com/evansims/openfga-php/blob/main/docs/API/Requests/ListObjectsRequest.md Get the object type to filter results by. Specifies the type of objects to include in the results. Only objects of this type will be considered when determining what the user can access. For example, "document," "folder," or "repository." ```APIDOC ## getType ### Description Get the object type to filter results by. Specifies the type of objects to include in the results. Only objects of this type will be considered when determining what the user can access. For example, "document," "folder," or "repository." ### Method ```php public function getType(): string ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string** - The object type to filter results by #### Response Example None ``` -------------------------------- ### Get Relationship Tuple Key for Expansion Source: https://github.com/evansims/openfga-php/wiki/API-Requests-ExpandRequest Retrieve the relationship tuple that serves as the starting point for relationship expansion. This defines the object and relation for which the authorization graph will be expanded, showing all users and user sets related to the specified object and relation. ```php public function getTupleKey(): OpenFGA\Models\TupleKeyInterface ``` -------------------------------- ### Initialize OpenFGA PHP Client Source: https://github.com/evansims/openfga-php/wiki/Stores Instantiate the OpenFGA client. Ensure the FGA_API_URL environment variable is set or provide a default. ```php readAssertions( $store, $authorizationModel )->unwrap(); // Write new assertions $newAssertions = new Assertions([ new Assertion( new TupleKey('user:anne', 'reader', 'document:budget'), true // expected result ) ]); $result = $assertionService->writeAssertions( $store, $authorizationModel, $newAssertions )->unwrap(); ``` -------------------------------- ### getRelation Source: https://github.com/evansims/openfga-php/wiki/API-Requests-ListUsersRequestInterface Get the relation to check for user access. Specifies the relationship type to evaluate when determining which users have access to the object. For example, "owner," "editor," "viewer," or "member." This defines what type of permission or relationship is being queried. ```APIDOC ## getRelation ### Description Get the relation to check for user access. Specifies the relationship type to evaluate when determining which users have access to the object. For example, "owner," "editor," "viewer," or "member." This defines what type of permission or relationship is being queried. ### Returns `string` — The relation name to check for user access ``` -------------------------------- ### Instantiate OpenFGA PHP Client Source: https://context7.com/evansims/openfga-php/llms.txt Demonstrates how to instantiate the `Client` class with different authentication methods: unauthenticated (local), pre-shared key (API token), and OAuth2 client credentials. ```php use OpenFGA\Client; use OpenFGA\Authentication\{ClientCredentialAuthentication, TokenAuthentication}; // Unauthenticated (local development) $client = new Client(url: 'http://localhost:8080'); // Pre-shared key (API token) $client = new Client( url: $_ENV['FGA_API_URL'], authentication: new TokenAuthentication( token: $_ENV['FGA_API_TOKEN'], ), ); // OAuth2 client credentials (Auth0 FGA / production) $client = new Client( url: $_ENV['FGA_API_URL'], authentication: new ClientCredentialAuthentication( clientId: $_ENV['FGA_CLIENT_ID'], clientSecret: $_ENV['FGA_CLIENT_SECRET'], issuer: $_ENV['FGA_ISSUER'], // e.g. https://tenant.us.auth0.com/oauth/token audience: $_ENV['FGA_AUDIENCE'], // e.g. https://api.us1.fga.dev/ ), ); ``` -------------------------------- ### get Source: https://github.com/evansims/openfga-php/wiki/API-Repositories-StoreRepositoryInterface Get a store by ID. Retrieves the details of an existing store including its name and timestamps. Use this to verify a store exists or to get its current metadata. ```APIDOC ## get ### Description Get a store by ID. Retrieves the details of an existing store including its name and timestamps. Use this to verify a store exists or to get its current metadata. ### Method `public function get(string $storeId): ResultInterface` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) `ResultInterface` containing the Store. #### Response Example None #### Error Handling Returns a Failure object with error details if the store is not found or an error occurs. ``` -------------------------------- ### startOperation Source: https://github.com/evansims/openfga-php/wiki/API-Observability-OpenTelemetryProvider Starts tracing a high-level OpenFGA API operation by creating a new trace span. The span includes relevant attributes such as store ID, authorization model ID, and operation-specific metadata. ```APIDOC ## startOperation ### Description Start tracing an OpenFGA API operation. Creates a new trace span for a high-level OpenFGA operation such as check, expand, or write operations. The span should include relevant attributes such as store ID, authorization model ID, and operation-specific metadata. ### Method `public function startOperation( string $operation, OpenFGA\Models\StoreInterface|string $store, ?OpenFGA\Models\AuthorizationModelInterface|string|null $model = NULL, array $attributes = [] ): object` ### Parameters #### Parameters - **$operation** (string) - Required - The OpenFGA operation name (for example 'check', 'expand', 'write_tuples') - **$store** (OpenFGA\Models\StoreInterface|string) - Required - The store being operated on - **$model** (OpenFGA\Models\AuthorizationModelInterface|null|string|null) - Optional - The authorization model being used - **$attributes** (array) - Required - ### Returns `object` - A span identifier or context that can be passed to endOperation() ``` -------------------------------- ### getOrCreateStore Source: https://github.com/evansims/openfga-php/wiki/API-Services-StoreService Gets an existing store or creates a new one with the given name. This convenience method first attempts to find a store by name among existing stores. If no store with the given name exists, it creates a new one. This is useful for idempotent store setup in development or testing scenarios. Note: This method lists all stores to find matches by name, which may be inefficient with large numbers of stores. ```APIDOC ## getOrCreateStore ### Description Gets an existing store or creates a new one with the given name. This convenience method first attempts to find a store by name among existing stores. If no store with the given name exists, it creates a new one. This is useful for idempotent store setup in development or testing scenarios. Note: This method lists all stores to find matches by name, which may be inefficient with large numbers of stores. ### Method `public function getOrCreateStore(string $name): OpenFGA\Results\FailureInterface|OpenFGA\Results\SuccessInterface` ### Parameters #### Path Parameters - **$name** (string) - Required - The name of the store to find or create ### Returns #### Success Response - `OpenFGA\Results\SuccessInterface` - Success containing the Store (existing or new) #### Error Response - `OpenFGA\Results\FailureInterface` - Failure with error details ``` -------------------------------- ### Usage Example for AuthorizationService in PHP Source: https://github.com/evansims/openfga-php/wiki/Integration Demonstrates how to bootstrap and use the AuthorizationService for checking permissions, granting access, and listing user resources. ```php // Bootstrap $config = [ 'url' => $_ENV['FGA_API_URL'], 'store_id' => $_ENV['FGA_STORE_ID'], 'model_id' => $_ENV['FGA_MODEL_ID'], 'client_id' => $_ENV['FGA_CLIENT_ID'], 'client_secret' => $_ENV['FGA_CLIENT_SECRET'], 'issuer' => $_ENV['FGA_ISSUER'], 'audience' => $_ENV['FGA_AUDIENCE'], ]; $auth = new AuthorizationService($config); // Check permissions if (!$auth->can($currentUserId, 'editor', 'document:readme')) { http_response_code(403); echo json_encode(['error' => 'Forbidden']); exit; } // Grant permission $auth->grant($newUserId, 'viewer', 'document:readme'); // List accessible documents $editableDocuments = $auth->listUserResources($currentUserId, 'editor', 'document'); ``` -------------------------------- ### Install Guzzle for Laravel Projects Source: https://github.com/evansims/openfga-php/wiki/Installation If Guzzle is not already installed in your Laravel project, use this command to add it. ```bash composer require guzzlehttp/guzzle ```