Current Location: Home> Latest Articles> Yii2 and Workerman Integration for WebSocket Communication: Detailed Tutorial

Yii2 and Workerman Integration for WebSocket Communication: Detailed Tutorial

gitbox 2025-07-15

Integrating Yii2 and Workerman for WebSocket Communication

Yii2 is a powerful PHP framework, while Workerman is a high-performance PHP socket framework that supports asynchronous operations. Combining these two frameworks enables developers to quickly implement WebSocket communication features. This article explains, with an example, how to integrate Workerman into Yii2 for WebSocket functionality.

Installing Yii2

First, you'll need to install Yii2. You can use the following composer command to install Yii2:

composer create-project --prefer-dist yiisoft/yii2-app-basic basic

This command will create a Yii2 application named 'basic' in the current directory.

Installing Workerman

Next, you need to install Workerman. Use composer to install it easily:

composer require workerman/workerman

After installation, you'll need to create a file named `worker.php` to run the Workerman service. Here’s an example of the code:

// worker.php
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
$worker = new Worker('websocket://0.0.0.0:8080');
$worker->onMessage = function($connection, $data) {
    // Handle received message
    $message = 'Received: ' . $data;
    // Send message to client
    $connection->send($message);
};
Worker::runAll();

The above code creates a WebSocket server that listens on port 8080. When a message is received, it is sent back to the client unchanged.

Creating Yii2 Controller and View

Next, in your Yii2 application, you'll need to create a controller to handle WebSocket requests. Here’s the code for the WebSocket controller:

// WebSocketController.php
namespace app\controllers;
use yii\web\Controller;
class WebSocketController extends Controller
{
    public $enableCsrfValidation = false;
    public function actionIndex()
    {
        // Create a websocket connection
        $connection = new \Workerman\Connection\TcpConnection('websocket://127.0.0.1:8080');
        $connection->onMessage = function($connection, $message) {
            // Handle received message
            $message = 'Received: ' . $message;
            // Send message to client
            $connection->send($message);
        };
        // Start websocket connection
        $connection->connect();
    }
}

In this controller, we use Workerman’s `TcpConnection` to create a WebSocket connection and define a callback function for handling messages that are received and sent back to the client.

Then, in the view file, we can create a button that, when clicked, sends a message to the server:

<?php
use yii\helpers\Html;
?>
<h1>WebSocket Example</h1>
<button id="sendButton">Send Message</button>
<script>
$(document).ready(function() {
    $('#sendButton').click(function() {
        var message = "Hello, server!";
        // Send message to server
        websocket.send(message);
    });
});
</script>

In this code, we use jQuery to bind a click event to the button. When clicked, it sends a message to the WebSocket server.

Configuring Routes

To make sure the Yii2 application can access the WebSocket controller, we need to configure the route in the application’s config file. Add the following code to the components array:

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        // Add websocket route
        '/websocket' => 'websocket/index'
    ],
],

With the above configuration, the /websocket route will point to the WebSocket controller we created earlier.

Conclusion

Through this article, you have learned how to integrate Workerman into a Yii2 application to implement WebSocket functionality. First, you installed Yii2 and Workerman via composer; then you created a worker file to run the Workerman service; after that, you created a WebSocket controller in the Yii2 application and added a button in the view to send messages to the server. Finally, you configured the route so the Yii2 application can access the WebSocket controller.

By following this example, you can easily integrate Workerman into your Yii2 application and add real-time communication features to your application, enhancing user experience.