PHPackages                             oncesk/yii-node-socket - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. oncesk/yii-node-socket

ActiveLibrary[HTTP &amp; Networking](/categories/http)

oncesk/yii-node-socket
======================

Реализует связь между php и client javascript по средству сокет соединения.

2.0.8(10y ago)6610.0k47[46 issues](https://github.com/oncesk/yii-node-socket/issues)[4 PRs](https://github.com/oncesk/yii-node-socket/pulls)PHP

Since Nov 3Pushed 7y ago15 watchersCompare

[ Source](https://github.com/oncesk/yii-node-socket)[ Packagist](https://packagist.org/packages/oncesk/yii-node-socket)[ RSS](/packages/oncesk-yii-node-socket/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (1)Versions (16)Used By (0)

Yii Node Socket
===============

[](#yii-node-socket)

[![Join the chat at https://gitter.im/oncesk/yii-node-socket](https://camo.githubusercontent.com/abe08b740a4156153736f791393ec4da6619c4be73212e75769f52edacc0e2b5/68747470733a2f2f6261646765732e6769747465722e696d2f4a6f696e253230436861742e737667)](https://gitter.im/oncesk/yii-node-socket?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Connect php, javascript, nodejs in one Yii application.

\####Yii1

Hi, if you need work with yii1 you can do it from ()

\####What you can do:

- send event(s) to all clients or in concrete room or in concrete channel
- now you can send events to single (concrete user) by user id!
- call some function or object method in window context
- you can change DOM model with jquery from php
- ability to set up data and get it in your javascript application
- send events from javascript for all clients or clients in concrete room or channel

\##Changes

- Updated for Yii 2.0
- Added Namespacing Updated for Yii 2.0
- Commposer settings updated to work with yii extension updates

\##Requirements

- linux/unix/windows
- git
- vps or dedicated server (for nodejs process)
- curl has to be installed or enabled

\#Installation

Install nodejs, if not installed see
Install extension

- Composer

```
{
        "require" : {
                "oncesk/yii-node-socket" : "2.0.4"
        }
}
```

- Using git clone

```
$> git clone https://github.com/oncesk/yii-node-socket.git
```

Now go to the folder where you install extension ***application.ext.yii-node-socket*** and execute

```
$> git submodule init
$> git submodule update
```

Yii configuration

- Configure console command in (***console/config/main.php***). You can use config below:

```
    'controllerMap' => [
        'node-socket' => '\YiiNodeSocket\NodeSocketCommand',
    ],
```

- Register Yii component, need to add into **frontend/config/main.php in your frontend application**:

```
		'nodeSocket' => [
		    'class' => '\YiiNodeSocket\NodeSocket',
		    'host' => 'localhost',
		    'allowedServerAddresses' => [
		        "localhost",
		        "127.0.0.1"
		    ],
		    'origin' => '*:*',
		    'sessionVarName' => 'PHPSESSID',
		    'port' => 3001,
		    'socketLogFile' => '/var/log/node-socket.log',
		],
```

> Notice: ***host*** should be a domain name like in you virtual host configuration or server ip address if you request page using ip address

- Configure aliases in the common config in (***common/config/main.php***).
- The first is for Yii to find the PHP Namespace and the second is to find the JS assets.
- You can use config below:

```
    'aliases' => [
        '@YiiNodeSocket' => '@vendor/oncesk/yii-node-socket/lib/php',
        '@nodeWeb' => '@vendor/oncesk/yii-node-socket/lib/js'
    ],
```

> Notice: if you will be use ***behaviors*** or node-socket models, you need to add nodeSocket component in ***preload*** components list

```
    'bootstrap' => ['log', 'nodeSocket'],
```

Install ***nodejs*** components in ***application.ext.yii-node-socket.lib.js.server***:

```
$> npm install
```

If you get errors issuing this command try the following:

```
$> npm install --no-bin-links
```

Congratulation, installation completed!

> Notice: if the name of the component will not be **nodeSocket**, your need to use special key in console command --componentName=component\_name

\###Console command actions

Use (**./yiic node-socket**)

```
$> ./yiic help node-socket # show help
$> ./yiic node-socket/start # start server
$> ./yiic node-socket/stop # stop server
$> ./yiic node-socket/restart # restart server
$> ./yiic node-socket/getPid # show pid of nodejs process
```

\##Definitions

- Frame - data package for nodejs server wrapped into Class. Per one request to nodejs server you can send only 1 frame. For send several frames at a time use Multiple frame.
- room - one or more clients in concrete namespace: every client can create room, other clients can join into concrete room, any client in room can send event in this room.

\##Javascript

Before use in javascript, register client stripts like here Depricated in Yii 2.0 - The Asset Manager registers the files on demand.

```
public function actionIndex() {
	// register node socket scripts
	// No longer needed - Yii::app()->nodeSocket->registerClientScripts();
}
```

\###Events

\###Work in javascript

Use `YiiNodeSocket` class

\####Start work

```
// create object
var socket = new YiiNodeSocket();

// enable debug mode
socket.debug(true);

socket.onConnect(function () {
	// fire when connection established
});

socket.onDisconnect(function () {
	// fire when connection close or lost
});

socket.onConnecting(function () {
	// fire when the socket is attempting to connect with the server
});

socket.onReconnect(function () {
	// fire when successfully reconnected to the server
});
```

\####Catch Events

Now events can be created only on PHP side. All data transmitted in json format. Into callback function data was pasted as javascript native object (or string, integer, depends of your PHP Frame config)

```
// add event listener
socket.on('updateBoard', function (data) {
	// do any action
});
```

\####Rooms

```
socket.onConnect(function () {
	socket.room('testRoom').join(function (success, numberOfRoomSubscribers) {
		// success - boolean, numberOfRoomSubscribers - number of room members
		// if error occurred then success = false, and numberOfRoomSubscribers - contains error message
		if (success) {
			console.log(numberOfRoomSubscribers + ' clients in room: ' + roomId);
			// do something

			// bind events
			this.on('join', function (newMembersCount) {
				// fire on client join
			});

			this.on('data', function (data) {
				// fire when server send frame into this room with 'data' event
			});
		} else {
			// numberOfRoomSubscribers - error message
			alert(numberOfRoomSubscribers);
		}
	});
});
```

\####Channels

Channel is very similar to the room, but you can controll access to channel for clients

```
// join to channel, join needed when you try subscribe to channel from javascript, if you subscribed to channel in php you can bind events without join
socket.onConnect(function () {
	var testChannel = socket.channel('test').join(function (success) {
		// success - boolean
		if (success) {
			// fore getting channel attributes
			console.log(this.getAttributes());

			// bind event listeners
			this.on('some_event', function (data) {
				// fire when server send frame into this room with 'data' event
			});
		} else {
			console.log(this.getError());
		}
	});

	// you can bind events handlers for some events without join
	// in this case you should be subscribed to `test` channel
	socket.channel('test').on('some_event', function (data) {
	});

});
```

\####Emit events

You can emit event to:

- all clients (including the event sender)
- all clients (excluding the event sender - broadcasting. Only javascript currently supports broadcasting. PHP broadcasting coming soon)
- clients in concrete room

Global events:

```
socket.emit('global.event', {
	message : {
		id : 12,
		title : 'This is a test message to all including sender'
	}
});

socket.broadcast.emit('global.event', {
	message : {
		id : 12,
		title : 'This is a test message to all excluding sender'
	}
});

socket.on('global.event', function (data) {
	console.log(data.message.title); // you will see in console `This is a test message`
});
```

Room event:

```
socket.onConnect(function () {
	var testRoom = socket.room('testRoom').join(function (success, numberOfRoomSubscribers) {
		// success - boolean, numberOfRoomSubscribers - number of room members
		// if error occurred then success = false, and numberOfRoomSubscribers - contains error message
		if (success) {
			console.log(numberOfRoomSubscribers + ' clients in room: ' + roomId);
			// do something

			// bind events
			this.on('message', function (message) {
				console.log(message);
			});

			this.on('ping', function () {
				console.log('Ping!');
			});

			this.emit('ping'); // emit ping event
		} else {
			// numberOfRoomSubscribers - error message
			alert(numberOfRoomSubscribers);
		}
	});

	// emit message event
	testRoom.emit('message', {
		message : {
			id : 12,
			title : 'This is a test message'
		}
	});
});
```

\####Shared Public Data

You can set shared data only from PHP using PublicData Frame (see below into PHP section). To access data you can use `getPublicData(string key, callback fn)` method

```
socket.getPublicData('error.strings', function (strings) {
	// you need to check if strings exists, because strings can be not setted or expired,
	if (strings) {
		// do something
	}
});
```

\##PHP

\####Behaviors

- YiiNodeSocket\\Behaviors\\ArChannel - can be used for create new channel. Example: You can attach this behavior to User, in result any user will have own channel, and other user can subscribe to events of concrete user.
- YiiNodeSocket\\Behaviors\\ArSubscriber - should be attached to object which can subscribe to some channel. Example: model User at a time can be channel and subscriber.

```
/**
 *
 * @method \YiiNodeSocket\Models\Channel getChannel()
 * @method \YiiNodeSocket\Frames\Event|null createEvent($name)
 */
class User extends CActiveRecord {

...

	public function behaviors() {
		return array(
			// attach channel behavior
			'channel' => array(
				'class' => '\YiiNodeSocket\Behaviors\ArChannel',
				'updateOnSave' => true
			),
			// attach subscriber behavior
			'subscriber' => array(
				'class' => '\YiiNodeSocket\Behaviors\ArSubscriber'
			)
		);
	}

...

}

// Example of subscribe

$user1 = new User();
$user1->setAttributes($attributes);
if ($user1->save()) {
	// imagine that $user1->id == 122
	// user channel was created and sent to nodejs server
	// subscriber was created and sent to nodejs server

	// create second user
	$user2 = User::model()->findByPk(121);

	// now we can subscribe one user to second user
	$user1->subscribe($user2);
	// and $user2 can catch events from $user1 channel like in twitter

}

// Example of emit event in concrete channel

$user = User::model()->findByPk(122);
if ($user) {

	// First method
	$event = $user->createEvent('test_event');
	if ($event) {
		// set event data
		$event->setData(array(
			'black', 'red', 'white'
		));
		// send event to user channel
		$event->send();
	}

	// Second method with getting channel
	$channel = $user->getChannel();
	if ($channel) {
		$event = $channel->createEvent('test_event');
		// set event data
		$event->setData(array(
			'black', 'red', 'white'
		));
		// send event to user channel
		$event->send();
	}
}

// Example of unsubscribe

$user1 = User::model()->findByPk(122);
$user2 = User::model()->findByPk(121);

$user1->unSubscribe($user2); // now $user2 can not catch events in channel of $user1
```

\####Client authorization

For authorizing client you need send special Authentication frame, you can do it in your ***user*** component in afterLogin event

```
protected function afterLogin($fromCookie) {
	parent::afterLogin($fromCookie);

	$frame = Yii::app()->nodeSocket->getFrameFactory()->createAuthenticationFrame();
	$frame->setUserId($this->getId());
	$frame->send();
}
```

After that, this user can receive events only for him. See example below, send event only for single (concrete) $user

```
// $user - the user model, which can receive this event

$event = Yii::app()->nodeSocket->getFrameFactory()->createUserEventFrame();
$event->setUserId($user->id);
$event->setEventName('message');
$event['text'] = 'Hello, how are you?';
$event->send();
```

and your javascript

```
var socket = new YiiNodeSocket();
socket.on('message', function (message) {
	console.log(message.text);
	// render message
});
```

\####Client scripts registration

```
public function actionIndex() {
	...

	Yii::app()->nodeSocket->registerClientScripts();

	...
}
```

\####Event frame

```
...

// create event frame
$frame = Yii::app()->nodeSocket->getFrameFactory()->createEventFrame();

// set event name
$frame->setEventName('updateBoard');

// set data using ArrayAccess interface
$frame['boardId'] = 25;
$frame['boardData'] = $html;

// or you can use setData(array $data) method
// setData overwrite data setted before

$frame->send();

...
```

\####Set up shared data

You can set expiration using ***setLifeTime(integer $lifetime)*** method of class PublicData

```
...

// create frame
$frame = Yii::app()->nodeSocket->getFrameFactory()->createPublicDataFrame();

// set key in storage
$frame->setKey('error.strings');

// set data
$frame->setData($errorStrings);

// you can set data via ArrayAccess interface
// $frame['empty_name'] = 'Please enter name';

// set data lifetime
$frame->setLifeTime(3600*2);	// after two hours data will be deleted from storage

// send
$frame->send();

...
```

\####Room events

```
...

// create frame
$frame = Yii::app()->nodeSocket->getFrameFactory()->createEventFrame();

// set event name
$frame->setEventName('updateBoard');

// set room name
$frame->setRoom('testRoom');

// set data
$frame['key'] = $value;

// send
$frame->send();

...
```

Only member of testRoom can catch this event

\####Invoke client function or method

In your PHP application you can invoke javascript function or method of object in window context.

```
$invokeFrame = Yii::app()->nodeSocket->getFrameFactory()->createInvokeFrame();
$invokeFrame->invokeFunction('alert', array('Hello world'));
$invokeFrame->send();	// alert will be showed on all clients
```

Extends from Event frame =&gt; you can send it into specific room

\####DOM manipulations with jquery

Task: you need update price on client side after price update in each product

```
...

$product = Product::model()->findByPk($productId);
if ($product) {
	$product->price = $newPrice;
	if ($product->save()) {
		$jFrame = Yii::app()->nodeSocket->getFrameFactory()->createJQueryFrame();
		$jFrame
			->createQuery('#product' . $product->id)
			->find('span.price')
			->text($product->price);
		$jFrame->send();
		// and all connected clients will can see updated price
	}
}

...
```

\####Send more than one frame per a time

Example 1:

```
$multipleFrame = Yii::app()->nodeSocket->getFrameFactory()->createMultipleFrame();

$eventFrame = Yii::app()->nodeSocket->getFrameFactory()->createEventFrame();

$eventFrame->setEventName('updateBoard');
$eventFrame['boardId'] = 25;
$eventFrame['boardData'] = $html;

$dataEvent = Yii::app()->nodeSocket->getFrameFactory()->createPublicDataFrame();

$dataEvent->setKey('error.strings');
$dataEvent['key'] = $value;

$multipleFrame->addFrame($eventFrame);
$multipleFrame->addFrame($dataEvent);
$multipleFrame->send();
```

Example 2:

```
$multipleFrame = Yii::app()->nodeSocket->getFrameFactory()->createMultipleFrame();

$eventFrame = $multipleFrame->createEventFrame();

$eventFrame->setEventName('updateBoard');
$eventFrame['boardId'] = 25;
$eventFrame['boardData'] = $html;

$dataEvent = $multipleFrame->createPublicDataFrame();

$dataEvent->setKey('error.strings');
$dataEvent['key'] = $value;

$multipleFrame->send();
```

\##PS

Sorry for my english :)

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance6

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community24

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 95.1% 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

Every ~69 days

Total

14

Last Release

3682d ago

Major Versions

0.1.x-dev → 1.0.12014-07-09

1.0.1 → 2.0.02014-10-27

### Community

Maintainers

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

---

Top Contributors

[![oncesk](https://avatars.githubusercontent.com/u/2046092?v=4)](https://github.com/oncesk "oncesk (215 commits)")[![doublehops](https://avatars.githubusercontent.com/u/389103?v=4)](https://github.com/doublehops "doublehops (3 commits)")[![fourteenmeister](https://avatars.githubusercontent.com/u/3837141?v=4)](https://github.com/fourteenmeister "fourteenmeister (2 commits)")[![hackmushroom](https://avatars.githubusercontent.com/u/7163415?v=4)](https://github.com/hackmushroom "hackmushroom (2 commits)")[![Xakki](https://avatars.githubusercontent.com/u/426468?v=4)](https://github.com/Xakki "Xakki (1 commits)")[![gitter-badger](https://avatars.githubusercontent.com/u/8518239?v=4)](https://github.com/gitter-badger "gitter-badger (1 commits)")[![marcinmisiak](https://avatars.githubusercontent.com/u/10694258?v=4)](https://github.com/marcinmisiak "marcinmisiak (1 commits)")[![Pashkinz92](https://avatars.githubusercontent.com/u/4114995?v=4)](https://github.com/Pashkinz92 "Pashkinz92 (1 commits)")

### Embed Badge

![Health badge](/badges/oncesk-yii-node-socket/health.svg)

```
[![Health](https://phpackages.com/badges/oncesk-yii-node-socket/health.svg)](https://phpackages.com/packages/oncesk-yii-node-socket)
```

###  Alternatives

[friendsofsymfony/rest-bundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony

2.8k73.3M319](/packages/friendsofsymfony-rest-bundle)[php-http/discovery

Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations

1.3k309.5M1.2k](/packages/php-http-discovery)[pusher/pusher-php-server

Library for interacting with the Pusher REST API

1.5k94.8M293](/packages/pusher-pusher-php-server)[react/http

Event-driven, streaming HTTP client and server implementation for ReactPHP

78026.4M414](/packages/react-http)[php-http/curl-client

PSR-18 and HTTPlug Async client with cURL

48347.0M384](/packages/php-http-curl-client)[smi2/phpclickhouse

PHP ClickHouse Client

84310.1M71](/packages/smi2-phpclickhouse)

PHPackages © 2026

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