Skip to main content
Multilingual TursoDB, MVCC & AI Agent database guides Read Engine Guide →
Turso Cloud SDKs Official SDKs PHP ORMs

Turso + Doctrine DBAL

Set up Turso in your PHP + Doctrine DBAL project in minutes

Doctrine DBAL

Prerequisites

Before you start, make sure you:

Download the latest build extension/driver binary you can see at Release page. It’s available for:

Get the installer:
    ```bash
    curl --proto '=https' --tlsv1.2 -sSf "https://darkterminal.github.io/turso-php-installer/dist/turso-php-installer.phar"
    ./turso-php-installer.phar
    ```

    Add as a global executable script:

    ```bash
    sudo mv turso-php-installer.phar /usr/local/bin/turso-php-installer
    ```

    **Usage**

    Install Turso Client PHP / libSQL Extension:

    ```bash
    turso-php-installer install
    ```

    Check on your console/terminal

    ```bash
    $ php --m | grep libsql
    liblibsql_php
    ```

    Update Turso Client PHP / libSQL Extension:

    ```bash
    turso-php-installer update
    ```

    Uninstall Turso Client PHP / libSQL Extension:

    ```bash
    turso-php-installer uninstall
    ```
</Accordion>
<Accordion title="Manual Configuration">
    - 📦 Extract the archive
    - 🗃 Locate somewhere in your machine
    - 💽 Copy a relative path that address that extension/driver
    - 📂 Open `php.ini` search `;extension` if you using nano (ctrl+w) then searching for it
    - 📝 add in the next-line `extension=liblibsql_php.so` (in Linux) without `;` at the begining

    Check on your console/terminal

    ```bash
    $ php --m | grep libsql
    liblibsql_php
    ```
</Accordion>

Now, LibSQL class is available in your PHP environment! You can use it everywhere in your PHP project 🎉

1. Configure database credentials

Get the database URL:

turso db show --url <database-name>

Get the database authentication token:

turso db tokens create <database-name>

Assign credentials to the environment variables inside .env.

TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
NOTE

Save this later when you need to connect to Remote and Embedded Replica

2. Create PHP Project

Create new directory:

mkdir your-awesome-php-project
cd your-awesome-php-project

3. Install Turso Doctrine DBAL

composer require tursodatabase/turso-doctrine-dbal

4. Configure database connection

Setup the environment variable in your Laravel application, choose what the type connection you need.

$params = [
    "url"               => ":memory:",
    'driverClass'       => \Turso\Doctrine\DBAL\Driver::class,
];
$params = [
    "url"               => "database.db",
    'driverClass'       => \Turso\Doctrine\DBAL\Driver::class,
];
$params = [
    "auth_token"        => getenv('TURSO_AUTH_TOKEN'),
    "sync_url"          => getenv('TURSO_DATABASE_URL'),
    'driverClass'       => \Turso\Doctrine\DBAL\Driver::class,
];
$params = [
    "url"               => "database.db",
    "auth_token"        => getenv('TURSO_AUTH_TOKEN'),
    "sync_url"          => getenv('TURSO_DATABASE_URL'),
    'driverClass'       => \Turso\Doctrine\DBAL\Driver::class,
];

Other environment variables (Embedded Replica Only)

Other environment variables (Embedded Replica Only)

sync_interval integer

Integer value representing synchronization interval in seconds (optional, default: 5).

read_your_writes boolean

Boolean value indicating whether to read your writes (optional, default: true).

encryption_key string

String value for encryption purposes (optional, default: empty).

5. Project Structure Example

src/
├── helpers.php
└── Todo.php
vendor/
composer.json
composer.lock
todo            # todo executable

Here you simple php todo cli + Doctrine BDAL

#!/usr/bin/env php
<?php

use Turso\Todo\CLI\Todo;

require_once __DIR__ . '/vendor/autoload.php';

$header = 'TODO CLI + TURSO';

echo $header . PHP_EOL;
function main()
{
    echo str_repeat('-', WIDTH - 18) . "  Todo CLI - " . VERSION . PHP_EOL;

    while (true) {
        echo "[L] List | [A] Add | [E] Edit | [D] Delete | [X] Exit" . PHP_EOL;
        echo "command: ";

        $choice = trim(fgets(STDIN));

        $app = new Todo();

        switch (strtolower($choice)) {
            case 'l':
                $app->listTodos();
                break;
            case 'a':
                $app->addTodo();
                clearScreen();
                break;
            case 'e':
                $app->editTodo();
                clearScreen();
                break;
            case 'd':
                $app->deleteTodo();
                clearScreen();
                break;
            case 'x':
                exit("Goodbye!" . PHP_EOL);
            default:
                echo "Invalid choice." . PHP_EOL;
                clearScreen();
        }
    }

    echo PHP_EOL;
}

main();
<?php

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;

const WIDTH = 100;
const VERSION = '1.0.0';

function clearScreen()
{
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        system('cls');
    } else {
        system('clear');
    }
}

function createConnection(): Connection
{
    $params = [
        "auth_token"        => getenv('TURSO_AUTH_TOKEN'),
        "sync_url"          => getenv('TURSO_DATABASE_URL'),
        'driverClass'       => \Turso\Doctrine\DBAL\Driver::class,
    ];

    $db = DriverManager::getConnection($params);
    
    return $db;
}
<?php

namespace Turso\Todo\CLI;

use Doctrine\DBAL\Connection;

class Todo
{

    private Connection $db;

    public function __construct()
    {
        $this->db = createConnection();
    }

    public function loadTodos(): array
    {
        $sql = "SELECT * FROM todos";
        return $this->db->fetchAllAssociative($sql);
    }

    public function saveTodo(string $todo): void
    {
        $sql = "INSERT INTO todos (name) VALUES (?)";
        $this->db->executeStatement($sql, [$todo]);
    }

    public function updateTodo(int $id, string $todo): void
    {
        $sql = "UPDATE todos SET name = ? WHERE id = ?";
        $this->db->executeStatement($sql, [$todo, $id]);
    }

    public function removeTodo(int $id): void
    {
        $sql = "DELETE FROM todos WHERE id = ?";
        $this->db->executeStatement($sql, [$id]);
    }

    public function listTodos()
    {
        $todos = $this->loadTodos();
        echo "\n" . "TODO-List   " . str_repeat('-', WIDTH - 12) . "\n\n";
        if (!empty($todos)) {
            foreach ($todos as $todo) {
                echo sprintf("[%d] %s\n", $todo['id'], $todo['name']);
            }
        } else {
            echo "Nothing...\n";
        }
        echo "\n" . str_repeat('-', WIDTH) . "\n";
    }

    public function addTodo()
    {
        echo "Enter the new To-Do: ";
        $todo = trim(fgets(STDIN));
        $this->saveTodo($todo);
        echo "To-Do added.\n";
    }

    public function editTodo()
    {
        $this->listTodos();
        echo "Enter the number of the To-Do to edit: ";
        $index = intval(trim(fgets(STDIN)));

        $findTodo = $this->db->executeQuery("SELECT * FROM todos WHERE id = ?", [$index])->fetchAssociative();

        if (!empty($findTodo)) {
            echo "Enter the new value: ";
            $todo = trim(fgets(STDIN));
            $this->updateTodo($findTodo['id'], $todo);
            echo "To-Do updated.\n";
        } else {
            echo "Invalid index.\n";
        }
    }

    public function deleteTodo()
    {
        $this->listTodos();
        echo "Enter the number of the To-Do to delete: ";
        $index = intval(trim(fgets(STDIN)));
        $findTodo = $this->db->executeQuery("SELECT * FROM todos WHERE id = ?", [$index])->fetchAssociative();
        if (!empty($findTodo)) {
            $this->removeTodo($findTodo['id']);
            echo "To-Do deleted.\n";
        } else {
            echo "Invalid index.\n";
        }
    }
}

6. Your PHP Application Ready!

PHP TODO CLI - TURSO

Examples

Synced from official Turso documentation ( tursodatabase/turso-docs · MIT License) Official Docs ↗
Search
Press Esc to close · Powered by Pagefind