L1 for Laravel

repository·master·Indexed 41 days ago

https://github.com/renoki-co/l1

Cloudflare bindings for Laravel applications that enable integration with Cloudflare services, specifically providing a native database connection and PDO-compatible interface for Cloudflare D1 via the CloudflareD1Connector, D1Connection, and D1Pdo classes.

Tokens
2.7K
Snippets
14
Records
14
Agent score
51%

What's inside L1

  1. Run tests with the simulated Cloudflare Worker

    master

    To run the test suite, you must first start the built-in Worker that simulates the Cloudflare API. This requires Node.js and npm.

    1. Start the worker:
    cd tests/worker
    npm ci
    npm run start
    1. In a separate terminal, run the PHPUnit tests:
    vendor/bin/phpunit
    # Start worker
    cd tests/worker
    npm ci
    npm run start
    
    # Run tests
    vendor/bin/phpunit
  2. Configure Cloudflare D1 in Laravel

    master

    To use D1 as a native Laravel database connection, add a d1 connection to your config/database.php file and configure your credentials in the .env file.

    // config/database.php
    'connections' => [
        'd1' => [
            'driver' => 'd1',
            'prefix' => '',
            'database' => env('CLOUDFLARE_D1_DATABASE_ID', ''),
            'api' => 'https://api.cloudflare.com/client/v4',
            'auth' => [
                'token' => env('CLOUDFLARE_TOKEN', ''),
                'account_id' => env('CLOUDFLARE_ACCOUNT_ID', ''),
            ],
        ],
    ]
    # .env
    CLOUDFLARE_TOKEN=
    CLOUDFLARE_ACCOUNT_ID=
    CLOUDFLARE_D1_DATABASE_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  3. Use Cloudflare D1 with raw PDO

    master

    Since D1 does not support standard SQL protocols, you can use the D1Pdo class and CloudflareD1Connector to proxy queries to the D1 /query endpoint via the Cloudflare API. Note that the dsn parameter in D1Pdo is irrelevant and can be set to sqlite::memory:.

    use RenokiCo\
    L1\
    D1\
    D1Pdo;
    use RenokiCo\
    L1\
    D1\
    D1PdoStatement;
    use RenokiCo\
    L1\
    CloudflareD1Connector;
    
    $pdo = new D1Pdo(
        dsn: 'sqlite::memory:', // irrelevant
        connector: new CloudflareD1Connector(
            database: 'your_database_id',
            token: 'your_api_token',
            accountId: 'your_cf_account_id',
        ),
    );
  4. Fetch results from D1PdoStatement

    master

    After executing a query, use fetchAll() to retrieve the results. You can control the format of the returned data using setFetchMode() or by passing the mode directly to fetchAll().

    • PDO::FETCH_ASSOC: Returns rows as associative arrays.
    • PDO::FETCH_OBJ: Returns rows as objects.

    Note: Other standard PDO fetch modes are currently unsupported and will throw a PDOException.

    // Set mode globally for the statement
    $statement->setFetchMode(PDO::FETCH_OBJ);
    $results = $statement->fetchAll();
    
    // Or pass it directly to fetchAll
    $results = $statement->fetchAll(PDO::FETCH_ASSOC);
  5. Execute queries using D1PdoStatement

    master

    The D1PdoStatement class allows you to execute SQL queries against Cloudflare D1 using a PDO-compatible interface. You can bind values to parameters using bindValue() or pass them directly to execute().

    When execute() is called, it performs the query against the D1 database. If the query fails or the D1 response indicates a failure, a PDOException is thrown containing the error message and code returned by the D1 API.

    Supported fetch modes in fetchAll() include:

    • PDO::FETCH_ASSOC: Returns an array of associative arrays.
    • PDO::FETCH_OBJ: Returns an array of objects.
    // Assuming $pdo is an instance of D1Pdo
    $statement = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $statement->bindValue(':id', 1, PDO::PARAM_INT);
    $statement->execute();
    
    $users = $statement->fetchAll(PDO::FETCH_ASSOC);
  6. Use CloudflareD1Connector to execute D1 queries

    master

    The CloudflareD1Connector class allows you to interact with Cloudflare D1 databases from Laravel. You can execute raw SQL queries by calling the databaseQuery method, passing the SQL string and an array of parameters to prevent SQL injection. This method returns a Saloon\Contracts\Response object containing the result of the query.

    use RenokiCo\L1\CloudflareD1Connector;
    
    $connector = new CloudflareD1Connector(
        database: 'your-database-id',
        token: 'your-cloudflare-api-token',
        accountId: 'your-cloudflare-account-id'
    );
    
    $response = $connector->databaseQuery(
        'SELECT * FROM users WHERE id = ?', 
        [1]
    );
  7. Use D1Connection for Cloudflare D1 database interactions

    master

    The D1Connection class extends Laravel's SQLiteConnection to provide a connection to Cloudflare D1 databases. It uses a specialized D1Pdo driver to bridge Laravel's database layer with the Cloudflare D1 environment.

    To access the underlying CloudflareD1Connector from a connection instance, use the d1() method.

    // Assuming $connection is an instance of D1Connection
    $connector = $connection->d1();
  8. Use D1Pdo for raw PDO interaction with Cloudflare D1

    master

    The D1Pdo class provides a PDO-compatible interface for interacting with Cloudflare D1 databases. It extends the standard PDO class, allowing you to use existing PDO-based logic while routing queries through the CloudflareD1Connector.

    Because D1 does not support standard SQL transactions in the same way a local database does, D1Pdo implements a simulated transaction state via beginTransaction(), commit(), and inTransaction() to maintain compatibility with code expecting a transactional PDO instance.

    use RenokiCo\L1\D1\Pdo\D1Pdo;
    use RenokiCo\L1\CloudflareD1Connector;
    
    // Assuming $connector is an instance of CloudflareD1Connector
    $dsn = 'your-dsn-string';
    $pdo = new D1Pdo($dsn, $connector);
    
    $statement = $pdo->prepare('SELECT * FROM users WHERE id = :id');
    $statement->execute(['id' => 1]);
  9. Execute D1 queries using D1QueryRequest

    master

    To execute a SQL query against a Cloudflare D1 database, instantiate D1QueryRequest. This class handles the construction of the POST request to the Cloudflare D1 API endpoint.

    It requires a connector, the name of the database, the SQL statement, and an array of parameters for the query. The request body is automatically formatted with sql and params keys.

    use RenokiCo\L1\D1\Requests\D1QueryRequest;
    
    $request = new D1QueryRequest(
        $connector,      // An instance of the Cloudflare connector
        'my-database',   // The name of your D1 database
        'SELECT * FROM users WHERE id = ?', // The SQL query
        [1]              // The parameters for the query
    );
  10. Access the CloudflareD1Connector from a D1Pdo instance

    master

    If you are working with a D1Pdo instance and need to access the underlying CloudflareD1Connector (for example, to access specific Cloudflare API configurations or connection details), you can use the d1() method.

    $connector = $pdo->d1();
  11. Manage simulated last insert IDs in D1Pdo

    master

    Since Cloudflare D1 may not behave like a traditional SQL database regarding lastInsertId(), D1Pdo allows you to manually track and retrieve insert IDs using setLastInsertId() and lastInsertId().

    By default, it tracks an ID associated with the key 'id'. You can also use custom names for different sequences.

    // Using the default 'id' key
    $pdo->setLastInsertId(null, 123);
    $id = $pdo->lastInsertId(); // returns 123
    
    // Using a custom name
    $pdo->setLastInsertId('order_id', 456);
    $orderId = $pdo->lastInsertId('order_id'); // returns 456