OpenSwoole Coroutine MySQL

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

MySQL Coroutine Support

Since OpenSwoole v4.3+ a new feature called hooks has been implemented, which allows OpenSwoole to listen for internal PHP API calls, take control and execute your code in a non-blocking way, allowing us to use well known and tested libraries like the PDO extension. The benefit of using hooks is it allows us to use existing PHP ecosystem tools and not force us to use any coroutine specific clients, instead OpenSwoole aims to support the existing ecosystem.

OpenSwoole hooks are not just for enabling coroutine support with MySQL, there are many different hooks which enable traditional blocking code to be executed in a non-blocking manner.

You can use PDO or MySQLi with OpenSwoole\Runtime::enableCoroutine to enable coroutine support for MySQL Clients.

The API is the same as PDO and MySQLi, by enabling the runtime hook you are free to query your database just like you would with PHP and MySQL.

Example

<?php

// Enable the hook for MySQL: PDO/MySQLi
co::set(['hook_flags' => OpenSwoole\Runtime::HOOK_TCP]);

// Setup a coroutine context
co::run(function() {

    // Execute a query inside a coroutine
    go(function () {

        // Already setup the $pdo connection before...

        $statement = $pdo->prepare("SELECT * FROM users LIMIT :limit, :offset");
        $statement->execute(['limit' => $limit, 'offset' => $offset]);
        $data = $statement->fetchAll();

        // Process $data result...

    });

});

It is only recommended to use hooks now instead of the old MySQL Coroutine Client as the example above allows you to use either PDO or MySQLi.

Also, the example above has created a coroutine context using co::run but this does not need to be done if you are running a OpenSwoole Server as it is done for you for each request.

If you are using the old MySQL OpenSwoole Client, please take note that it does not support the use of bind_param and that is why it is recommended to use the hook functionality instead

Last updated on September 20, 2022