When using Swoole with Yii2, accessing the database connection requires careful consideration because Swoole is a long-running process, while Yii2 (by default) is designed for short-lived, request-scoped execution. This difference introduces challenges related to:
- Connection Persistence: If a database connection is established once when the Swoole worker starts and then shared across multiple requests, it can lead to issues like "MySQL gone away" errors after inactivity, or concurrent access problems if not properly handled.
- State Management: Yii2's
Yii::$app instance and its components (like db, request, response, user, etc.) are designed to be re-initialized for each request in a traditional PHP-FPM environment. In Swoole, if not reset, these components persist between requests, leading to shared state and potential data leaks or incorrect context.
Here's how to properly manage database connections with Yii2 on Swoole, from basic to recommended approaches:
The Core Problem: Request Scope vs. Process Scope
In a traditional PHP-FPM model, every request is a new process (or a recycled one that's completely clean). So, Yii::$app and Yii::$app->db are created fresh for each request.
With Swoole, a worker process starts once and handles many requests. If you initialize Yii::$app and its components (db included) once in onWorkerStart, they will be shared across all subsequent requests handled by that worker. This is problematic.
Solutions
1. Simple but Less Efficient: Re-instantiate Yii::$app and db on Every Request
This approach mimics the PHP-FPM behavior by creating a fresh Yii application instance for every single incoming request. While it ensures isolation, it incurs the overhead of bootstrapping Yii and establishing a new DB connection for each request.
server.php example:
<?php
// Define Yii application constants (if not already defined in your entry script)
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
// Autoloading
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/config/web.php'; // Your Yii2 web config
$http = new Swoole\Http\Server("0.0.0.0", 9501);
$http->on('start', function ($server) {
echo "Swoole http server is started at http://127.0.0.1:9501\n";
});
$http->on('request', function ($request, $response) use ($config) {
// --- IMPORTANT: Resetting Yii::$app for each request ---
// Clear previous application instance if any
Yii::$app = null;
// Simulate PHP-FPM environment variables
$_SERVER = [];
foreach ($request->server as $key => $value) {
$_SERVER[strtoupper($key)] = $value;
}
$_GET = $request->get ?? [];
$_POST = $request->post ?? [];
$_FILES = $request->files ?? [];
$_COOKIE = $request->cookie ?? [];
$_REQUEST = array_merge($_GET, $_POST, $_COOKIE);
// Initialize Yii application
try {
$application = new yii\web\Application($config);
$application->run();
// Capture output buffer (if Yii renders views)
$content = ob_get_clean();
// Set response headers
foreach ($application->response->headers->toArray() as $name => $values) {
foreach ($values as $value) {
$response->header($name, $value);
}
}
$response->status($application->response->statusCode);
$response->end($content);
} catch (\Throwable $e) {
// Basic error handling
error_log($e->getMessage() . "\n" . $e->getTraceAsString());
$response->status(500);
$response->end('An internal server error occurred.');
} finally {
// Ensure application instance is cleared after response (important for next request)
// If you were using yii\console\Application or background tasks, you'd handle this differently.
Yii::$app = null;
// Optionally, reset other global states if necessary
// For basic web apps, Yii::$app = null is usually sufficient to release resources.
}
});
$http->start();
Pros:
- Ensures complete isolation between requests.
- Simplest to understand conceptually.
Cons:
- Performance Overhead: Re-bootstrapping Yii and re-establishing DB connections for every request is slow and inefficient. This largely negates the benefits of Swoole's persistent nature.
- Not recommended for high-performance applications.
2. Recommended: Use yiisoft/yii-swoole
This is the official and recommended way to run Yii2 applications on Swoole. It handles the complexities of context isolation, Yii::$app lifecycle management, and integrates with connection pooling.
Key Features of yiisoft/yii-swoole:
- Automatic Context Reset: It takes care of resetting
Yii::$app, $_GET, $_POST, $_SERVER, etc., for each request, ensuring request isolation.
- Connection Pooling Integration: It integrates with
yiisoft/db-swoole (or allows custom pooling) to manage persistent database connections efficiently.
- Error Handling: Better error handling in a persistent environment.
- Console Commands: Allows running Yii console commands within Swoole.
Steps:
a. Install Necessary Packages:
composer require yiisoft/yii-swoole
composer require yiisoft/db-swoole # For database connection pooling
b. Configure your Yii2 web.php (or console.php if using yii-swoole for console commands)
No special configuration needed for the DB component itself in web.php yet. You'll configure the Swoole server to use the pooling capabilities.
// config/web.php
return [
// ...
'components' => [
'db' => [
'class' => 'yii\db\Connection', // Still use the standard Yii2 connection
'dsn' => 'mysql:host=localhost;dbname=your_database',
'username' => 'your_user',
'password' => 'your_password',
'charset' => 'utf8',
// ... other DB configurations
],
// ...
],
// ...
];
c. Create your Swoole Server File (server.php):
This file will bootstrap the yii-swoole server.
<?php
// server.php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
// Load your Yii2 application configuration
$webConfig = require __DIR__ . '/config/web.php';
$consoleConfig = require __DIR__ . '/config/console.php'; // Only if you plan to run console commands
// Instantiate the Swoole application server
$server = new \Yiisoft\Yii\Swoole\Application($webConfig, $consoleConfig);
// Configure the HTTP server (Swoole settings)
$server->args([
'host' => '0.0.0.0',
'port' => 9501,
'options' => [
'worker_num' => swoole_cpu_num(), // Number of worker processes
'daemonize' => 0, // Run as a daemon (1 for production)
'max_request' => 1000, // Max requests per worker before recycling
'enable_static_handler' => true, // Serve static files directly by Swoole
'document_root' => dirname(__DIR__) . '/web', // Path to your web/ directory
// Other Swoole options...
],
]);
// Configure connection pooling for your DB component
// This tells `yii-swoole` to use `yiisoft/db-swoole` for the 'db' component.
$server->withPool('db', [
'class' => \Yiisoft\Db\Swoole\Connection::class,
'config' => [
'dsn' => 'mysql:host=localhost;dbname=your_database',
'username' => 'your_user',
'password' => 'your_password',
'charset' => 'utf8',
],
'poolConfig' => [
'min' => 5, // Minimum connections in the pool
'max' => 20, // Maximum connections in the pool
'waitTimeout' => 3, // Seconds to wait for a connection
'idleTimeout' => 60, // Seconds a connection can be idle before being closed
],
]);
// Start the server
$server->start();
d. Run the Server:
php server.php
Now, when you access your Yii2 application via http://localhost:9501, the yiisoft/yii-swoole package will handle the lifecycle, and yiisoft/db-swoole will manage your database connections within a pool. When Yii::$app->db is accessed, it will automatically fetch a connection from the pool and return it to the pool after the request.
Explanation of Connection Pooling with yiisoft/db-swoole:
Instead of creating a new yii\db\Connection (and underlying PDO object) on every request, yiisoft/db-swoole maintains a pool of PDO connections.
- When a request needs a database connection, it
borrows one from the pool.
- After the request is processed, the connection is
returned to the pool for reuse by another request.
- This significantly reduces the overhead of establishing new connections and keeps connections warm.
3. Advanced: Custom Connection Pooling (if yiisoft/db-swoole doesn't fit)
If you have very specific pooling requirements or need to integrate with a different pooling library (e.g., a Redis pool, or a custom PDO pool not covered by yiisoft/db-swoole), you would need to implement your own Connection class that interacts with a pool.
Concept:
- Initialize the Pool: In
onWorkerStart, initialize your connection pool (e.g., an array of PDO objects or a Swoole\Database\PDOPool instance if you're using Swoole's native pooling). This pool instance should be stored in a static property or a global variable accessible by workers.
- Custom
yii\db\Connection: Create a custom class, e.g., app\components\PooledDbConnection, that extends yii\db\Connection.
- Override
createPdoInstance() to fetch a PDO object from your pre-initialized pool.
- Override
__destruct() or add a release() method to return the PDO object back to the pool.
- Configure Yii2: In your
web.php config, change the db component's class to your custom PooledDbConnection.
This approach is complex and requires deep understanding of both Yii2's DB component and Swoole's lifecycle. yiisoft/db-swoole essentially implements this pattern for you, making it largely unnecessary to do it manually unless you have very unique needs.
Key Considerations for Swoole + Yii2 Database Access
- State Management: Always assume no shared state between requests. Any request-specific data (e.g., user ID, session data) must be isolated per request.
yiisoft/yii-swoole handles this for Yii::$app components.
- Global Variables: Avoid relying on global variables for request-specific data.
onWorkerStart vs. onWorkerStop: Use onWorkerStart to initialize shared, long-lived resources like connection pools. Use onWorkerStop to gracefully close them.
max_request and reload_async: Swoole's max_request option helps mitigate potential memory leaks by restarting workers after a certain number of requests. reload_async allows for graceful reloads without dropping connections.
- Error Handling: Ensure robust error logging and handling, as a single unhandled error can crash a worker and affect many subsequent requests.
- Testing: Thoroughly test your application under load to ensure connection stability and proper state isolation.
For most Yii2 applications running on Swoole, yiisoft/yii-swoole combined with yiisoft/db-swoole is the best practice for managing database connections efficiently and correctly.