PHPackages                             phuongdev89/yii2-socketio - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. phuongdev89/yii2-socketio

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

phuongdev89/yii2-socketio
=========================

The simple and powerful socketio for the Yii2 framework

1.2.4(3y ago)087MITPHP

Since May 20Pushed 1y agoCompare

[ Source](https://github.com/phuongdev89/yii2-socketio)[ Packagist](https://packagist.org/packages/phuongdev89/yii2-socketio)[ RSS](/packages/phuongdev89-yii2-socketio/feed)WikiDiscussions 2.0-dev Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (3)Used By (0)

Socket.io Yii extension
=======================

[](#socketio-yii-extension)

Use all power of socket.io in your Yii 2 project.

Install
-------

[](#install)

##### Install nodejs (tested with node 18)

[](#install-nodejs-tested-with-node-18)

```
    curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
    sudo apt-get install -y nodejs

```

##### Add to `composer.json`

[](#add-to-composerjson)

```
{
    "require" : {
        "phuongdev89/yii2-socketio": "^2"
    },
    ...
    "scripts" : {
        "post-install-cmd": "cd vendor/phuongdev89/yii2-socketio && /usr/bin/npm install",
        "post-update-cmd": "cd vendor/phuongdev89/yii2-socketio && /usr/bin/npm install"
    }
}
```

Config
------

[](#config)

#### Console config (simple fork)

[](#console-config-simple-fork)

```
    'controllerMap' => [
        'socketio' => [
            'class' => \phuongdev89\socketio\commands\SocketIoCommand::class,
            'server' => 'localhost:1367'
        ],
    ]
```

###### Start sockeio server

[](#start-sockeio-server)

```
    php yii socketio/start
```

###### Stop sockeio server

[](#stop-sockeio-server)

```
    php yii socketio/stop
```

##### Common config

[](#common-config)

```
    'components' =>[
        'broadcastEvent' => [
            'class' => \phuongdev89\socketio\components\BroadcastEvent::class,
            'nsp' => 'some_unique_key', //must be changed
            // Namespaces with events folders
            'namespaces' => [
                'app\socketio',
            ]
        ],
        'broadcastDriver' => [
            'class' => \phuongdev89\socketio\components\BroadcastDriver::class,
            'hostname' => 'localhost',
            'port' => 6379,
        ],
    ]
```

Usage
-----

[](#usage)

### Publisher

[](#publisher)

Create publisher from server to client

```
    use phuongdev89\socketio\events\EventInterface;
    use phuongdev89\socketio\events\EventPubInterface;

    class CountEvent implements EventInterface, EventPubInterface
    {
        /**
         * Channel name. For client side this is nsp.
         */
        public static function broadcastOn(): array
        {
            return ['notifications'];
        }

        /**
         * Event name
         */
        public static function name(): string
        {
            return 'update_notification_count';
        }

        /**
         * Emit client event
         * @param array $data
         * @return array
         */
        public function fire(array $data): array
        {
            return $data;
        }
    }
```

On client using socketio to receive data from server

```
    var socket = io('localhost:1367/notifications');
    socket.on('update_notification_count', function(data){
        console.log(data)
    });
```

Using to broadcast data to client

```
    //Run broadcast to client
    \phuongdev89\socketio\Broadcast::emit(CountEvent::name(), ['count' => 10]);
```

### Receiver

[](#receiver)

Create receiver from client to server

```
    use phuongdev89\socketio\events\EventInterface;
    use phuongdev89\socketio\events\EventSubInterface;

    class MarkAsReadEvent implements EventInterface, EventSubInterface
    {
        /**
         * Changel name. For client side this is nsp.
         */
        public static function broadcastOn(): array
        {
            return ['notifications'];
        }

        /**
         * Event name
         */
        public static function name(): string
        {
            return 'mark_as_read_notification';
        }

        /**
         * Emit client event
         * @param array $data
         * @return array
         */
        public function handle(array $data)
        {
            // Mark notification as read
            // And call client update
            file_put_contents(\Yii::getAlias('@app/file.txt'), json_encode($data));
        }
    }
```

On client using socketio to emit data to server

```
    var socket = io('localhost:1367/notifications');
    socket.emit('mark_as_read_notification', {id: 10});
```

### Receiver with checking from client to server

[](#receiver-with-checking-from-client-to-server)

You can have publisher and receiver in one event. If you need check data from client to server you should use:

- EventPolicyInterface

```
    use phuongdev89\socketio\events\EventSubInterface;
    use phuongdev89\socketio\events\EventInterface;
    use phuongdev89\socketio\events\EventPolicyInterface;

    class MarkAsReadEvent implements EventInterface, EventSubInterface, EventPolicyInterface
    {
        /**
         * Changel name. For client side this is nsp.
         */
        public static function broadcastOn(): array
        {
            return ['notifications'];
        }

        /**
         * Event name
         */
        public static function name(): string
        {
            return 'mark_as_read_notification';
        }

        /**
        * @param $data
        * @return bool
        */
        public function can($data): bool
        {
            // Check data from client
            return true;
        }

        /**
         * Emit client event
         * @param array $data
         * @return array
         */
        public function handle(array $data)
        {
            // Mark notification as read
            // And call client update
            file_put_contents(\Yii::getAlias('@app/file.txt'), json_encode($data));
        }
    }
```

### Subscribe room

[](#subscribe-room)

Socket.io has room function. If you need it, you should implement `EventRoomInterface`

```
    use phuongdev89\socketio\events\EventPubInterface;
    use phuongdev89\socketio\events\EventInterface;
    use phuongdev89\socketio\events\EventRoomInterface;

    class CountEvent implements EventInterface, EventPubInterface, EventRoomInterface
    {
        /**
         * User id
         * @var int
         */
        protected $user_id;

        /**
         * Channel name. For client side this is nsp.
         */
        public static function broadcastOn(): array
        {
            return ['notifications'];
        }

        /**
         * Event name
         */
        public static function name(): string
        {
            return 'update_notification_count';
        }

        /**
         * Socket.io room
         * @return string
         */
        public function room(): string
        {
            return 'user_id_' . $this->user_id;
        }

        /**
         * Emit client event
         * @param array $data
         * @return array
         */
        public function fire(array $data): array
        {
            $this->user_id = $data['user_id'];
            return [
                'count' => 10,
            ];
        }
    }
```

### Subscribe room with event

[](#subscribe-room-with-event)

You should use trait `ListenTrait`

```
    use phuongdev89\socketio\events\EventPubInterface;
    use phuongdev89\socketio\events\EventInterface;
    use phuongdev89\socketio\events\EventRoomInterface;
    use phuongdev89\socketio\traits\ListenTrait;

    class CountEvent implements EventInterface, EventPubInterface, EventRoomInterface
    {
        use ListenTrait;
        /**
         * User id
         * @var int
         */
        protected $userId;

        /**
         * Channel name. For client side this is nsp.
         */
        public static function broadcastOn(): array
        {
            return ['notifications'];
        }

        /**
         * Socket.io room
         * @return string
         */
        public function room(): string
        {
            return 'user_id_' . $this->userId;
        }

        /**
         * Emit client event
         * @param array $data
         * @return array
         */
        public function fire(array $data): array
        {
            $this->userId = $data['userId'];
            return [
                'count' => 10,
            ];
        }

        public function handle(array $data)
        {
            $this->listen($data); //must place before your code
            file_put_contents(\Yii::getAlias('@app/../file.txt'), serialize($data));
        }

        public function onLeave($room_id)
        {
         // TODO: Implement onLeave() method.
        }

        public function onDisconnect($room_id)
        {
         // TODO: Implement onDisconnect() method.
        }

        public function onJoin($room_id)
        {
         // TODO: Implement onJoin() method.
        }
    }
```

On client using socketio to join the room, and listen data

```
    var socket = io('localhost:1367/notifications');
    socket.emit('join', {room: 'user_id_10'});
    // Now you will receive data from 'room-10'
    socket.on('update_notification_count', function(data){
        console.log(data)
    });
    // You can leave room
    socket.emit('leave');
```

Using to broadcast data to client on the room

```
    //Run broadcast to user id = 10
    \phuongdev89\socketio\Broadcast::emitToRoom(CountEvent::class, [
        'count' => 4,
        'user_id' => 10,//push data to room-10
    ]);
```

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance28

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 79.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1452d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b606411df0cf562fe1d77d5ee80c3ef2e2c34a06d93470a4127c8910132ba258?d=identicon)[phuongdev89](/maintainers/phuongdev89)

---

Top Contributors

[![lexxorlov](https://avatars.githubusercontent.com/u/7910574?v=4)](https://github.com/lexxorlov "lexxorlov (23 commits)")[![orlov-alexey](https://avatars.githubusercontent.com/u/95412821?v=4)](https://github.com/orlov-alexey "orlov-alexey (5 commits)")[![phuongdev89](https://avatars.githubusercontent.com/u/7648033?v=4)](https://github.com/phuongdev89 "phuongdev89 (1 commits)")

###  Code Quality

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/phuongdev89-yii2-socketio/health.svg)

```
[![Health](https://phpackages.com/badges/phuongdev89-yii2-socketio/health.svg)](https://phpackages.com/packages/phuongdev89-yii2-socketio)
```

###  Alternatives

[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

728272.9k20](/packages/civicrm-civicrm-core)[shlinkio/shlink

A self-hosted and PHP-based URL shortener application with CLI and REST interfaces

4.8k4.3k](/packages/shlinkio-shlink)[overtrue/php-opencc

中文简繁转换，支持词汇级别的转换、异体字转换和地区习惯用词转换（中国大陆、台湾、香港、日本新字体）。基于 \[BYVoid/OpenCC\](https://github.com/BYVoid/OpenCC) 数据实现。

12130.7k](/packages/overtrue-php-opencc)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
