Introduction - evansims/openfga-php GitHub Wiki

This guide takes you through building your first authorization. You'll install the SDK, connect to OpenFGA, and check your first permission.


Prerequisites


Anatomy of Authorization

Authorization with OpenFGA boils down to three things:

  • A store, which acts like a database for your permissions.
  • An authorization model, which defines what permissions exist. Like "documents can have viewers and editors."
  • The relationship tuples, which establish specific permissions between users and resources. Like "Alice can view document:readme."

With those elements in place, you can then use permission queries to have OpenFGA answer questions like "can Alice edit this document?"


Quickstart

1. Start OpenFGA

The quickest method is Docker — one command gets you up and running:

docker run -d -p 8080:8080 --name openfga openfga/openfga run

Your server is now accessible at http://localhost:8080.


2. Install the SDK

Use Composer to add the SDK to your application:

composer require evansims/openfga-php

In some cases you may need to install additional dependencies for the SDK.


3. Integrate the SDK

3.1. Create a Client

Begin integrating the SDK by initializing an SDK Client in your application:

<?php

declare(strict_types=1);

use OpenFGA\Client;

use function OpenFGA\{allowed, dsl, model, store, tuple, write};

$client = new Client(
    url: $_ENV['FGA_API_URL'] ?? 'http://localhost:8080',
);

In a production environment you'll want authentication and error handling.


3.2. Create a Store

$storeId = store(
    name: 'example-document-system',
    client: $client,
);

echo "Created store: {$storeId}\n";

3.3 Define a Model

$dsl = <<<'DSL'
        model
            schema 1.1

        type user

        type document
            relations
            define viewer: [user]
            define editor: [user]
    DSL;

$model = dsl(
    dsl: $dsl,
    client: $client,
);

3.4 Create a Model

$modelId = model(
    model: $model,
    store: $storeId,
    client: $client,
);

echo "Created model: {$modelId}\n";

3.5 Grant Permission

write(
    client: $client,
    store: $storeId,
    model: $modelId,
    tuples: tuple('user:alice', 'viewer', 'document:readme'),
);

echo "Granted alice viewer permission on readme\n";

3.6 Check Permission

$canView = allowed(
    client: $client,
    store: $storeId,
    model: $modelId,
    tuple: tuple('user:alice', 'viewer', 'document:readme'),
);

echo $canView ? '✅ Alice can view readme' : '❌ Access denied';

4. Run the Example

  1. Make sure your OpenFGA server is running
  2. Save the code as example.php
  3. Run php example.php
⚠️ **GitHub.com Fallback** ⚠️