PHP code example of curentis / openfga-php

1. Go to this page and download the library: Download curentis/openfga-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

curentis / openfga-php example snippets


use Curentis\OpenFga\Client\ClientConfiguration;
use Curentis\OpenFga\Client\OpenFgaClientFactory;
use Curentis\OpenFga\Client\OpenFgaClientInterface;
use Curentis\OpenFga\Client\Request\ClientCheckRequest;
use Curentis\OpenFga\Client\Request\ClientTupleKey;
use Curentis\OpenFga\Client\Request\ClientWriteRequest;
use Curentis\OpenFga\Model\WriteAuthorizationModelBody;

/** @var OpenFgaClientInterface $fga */
$fga = OpenFgaClientFactory::create(new ClientConfiguration(
    apiUrl: getenv('FGA_API_URL') ?: 'http://localhost:8080',
));

$storeId = $fga->createStore('quickstart')->id;
$fga = $fga->withStoreId($storeId);

$modelId = $fga->writeAuthorizationModel(WriteAuthorizationModelBody::fromArray([
    'schema_version' => '1.1',
    'type_definitions' => [
        ['type' => 'user'],
        [
            'type' => 'document',
            'relations' => ['viewer' => ['this' => new stdClass()]],
            'metadata' => [
                'relations' => [
                    'viewer' => ['directly_related_user_types' => [['type' => 'user']]],
                ],
            ],
        ],
    ],
]))->authorizationModelId;
$fga = $fga->withAuthorizationModelId($modelId);

$fga->write(new ClientWriteRequest(writes: [
    new ClientTupleKey('user:anne', 'viewer', 'document:roadmap'),
]));

var_dump($fga->check(new ClientCheckRequest('user:anne', 'viewer', 'document:roadmap'))->allowed); // true

use Curentis\OpenFga\Credentials\ApiToken;
use Curentis\OpenFga\Credentials\ClientCredentials;

// Bearer API token (hosted OpenFGA)
new ClientConfiguration(credentials: new ApiToken($apiToken));

// OAuth2 client credentials
new ClientConfiguration(credentials: new ClientCredentials(
    clientId: '...',
    clientSecret: '...',
    apiTokenIssuer: 'https://auth.example.com',
    apiAudience: 'https://api.us1.fga.dev/',
));

$fga = OpenFgaClientFactory::create(new ClientConfiguration(
    componentFactory: new MyComponentFactory(),
));
bash
composer 
bash
export FGA_API_URL=http://localhost:8080
php examples/quickstart.php