# Turso + Doctrine DBAL

> Set up Turso in your PHP + Doctrine DBAL project in minutes
> Canonical HTML: https://tursodb.cn/docs/sdk/php/orm/doctrine-dbal/
> Upstream Source (MIT): https://docs.turso.tech/sdk/php/orm/doctrine-dbal
> Language: en

---
![Doctrine DBAL](/images/turso-docs/guides/doctrine-dbal-banner.png)

## Prerequisites

Before you start, make sure you:

* [Install the Turso CLI](/docs/cli/installation/)
* [Sign up or login to Turso](/docs/cli/authentication/#signup)
* Have an PHP Application with Doctrine DBAL

Download the latest build extension/driver binary you can see at [Release](https://github.com/tursodatabase/turso-client-php/releases) page. It's available for:

- Linux
- Mac/Darwin
- Windows (WSL) / [Devcontainer](https://github.com/darkterminal/turso-docker-php)

<AccordionGroup>
    <Accordion title="Turso PHP Installer (Linux/macOS only)">
        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>

</AccordionGroup>

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:

```bash
turso db show --url <database-name>
```

Get the database authentication token:

```bash
turso db tokens create <database-name>
```

Assign credentials to the environment variables inside `.env`.

```bash
TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
```

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

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

</div></div>


**2. Create PHP Project**

Create new directory:

```bash
mkdir your-awesome-php-project
cd your-awesome-php-project
```

**3. Install Turso Doctrine DBAL**

```bash
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.

```php In-Memory Only
$params = [
    "url"               => ":memory:",
    'driverClass'       => \Turso\Doctrine\DBAL\Driver::class,
];
```

```php Local Only
$params = [
    "url"               => "database.db",
    'driverClass'       => \Turso\Doctrine\DBAL\Driver::class,
];
```

```php Remote Only
$params = [
    "auth_token"        => getenv('TURSO_AUTH_TOKEN'),
    "sync_url"          => getenv('TURSO_DATABASE_URL'),
    'driverClass'       => \Turso\Doctrine\DBAL\Driver::class,
];
```

```php Embedded Replica
$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**

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

Here you simple php todo cli + Doctrine BDAL

```php todo
#!/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 src/helpers.php
<?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 src/Todo.php
<?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](https://i.imgur.com/dmrPFr2.png)

## Examples

<div class="doc-cards">
<a class="doc-card" href="https://github.com/tursodatabase/example/php-todo-cli-doctrine-dbal/tree/master" target="_blank" rel="noopener noreferrer"><div class="doc-card-title"><span>PHP Todo CLI + Doctrine DBAL</span><span class="doc-card-arrow" aria-hidden="true">↗</span></div><p class="doc-card-desc">See the full source code</p></a>
<a class="doc-card" href="https://github.com/tursodatabase/example/symfony7-rest-api-crud/tree/master" target="_blank" rel="noopener noreferrer"><div class="doc-card-title"><span>Symfony Rest API CRUD</span><span class="doc-card-arrow" aria-hidden="true">↗</span></div><p class="doc-card-desc">See the full source code</p></a>
</div>
