Swoole Coroutine MySQL

Notice: the documentation is suitable for PHP extension swoole until v4.7.1, we only support PHP extension openswoole from v4.7.1

MySQL Coroutine Support

Since Swoole v4.3+ a new feature called hooks has been implemented, which allows Swoole 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 Swoole aims to support the existing ecosystem.

Swoole 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 Swoole\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' => SWOOLE_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 Swoole Server as it is done for you for each request.

If you are using the old MySQL Swoole 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