Object and Resource Persistence
In traditional web development, objects, data, resources, etc. created by PHP are all released once the request is completed, making persistence difficult. However, in Workerman, this can be easily achieved.
If you want to permanently store certain data resources in memory in Workerman, you can place resources into global variables or static members of a class.
For example, the following code:
Uses a global variable $connection_count to keep track of the number of client connections for the current process.
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
// Global variable to store the number of client connections for the current process
$connection_count = 0;
$worker = new Worker('tcp://0.0.0.0:1236');
$worker->onConnect = function(TcpConnection $connection)
{
// Increment connection count by 1 when a new client connects
global $connection_count;
++$connection_count;
echo "now connection_count=$connection_count\n";
};
$worker->onClose = function(TcpConnection $connection)
{
// Decrement connection count by 1 when a client disconnects
global $connection_count;
$connection_count--;
echo "now connection_count=$connection_count\n";
};