ratacibernetica/yii2-node-socket

There is no license information available for the latest version (v1.0) of this package.

This is a fork of oncesk/yii-node-socket

v1.0 2015-10-02 15:46 UTC

This package is not auto-updated.

Last update: 2024-10-26 19:37:41 UTC


README

####Disclaimer This fork is under development to make it work with Yii2. As of now, i haven't checked the subscription feature, Many parts of code have been rewritten and tested only in a project, so i guess this doesn't work not out of the box .

Be warned.

Yii2 Node Socket

Connect php, javascript, nodejs in one Yii application.

####Yii1

Hi, if you need work with yii1 you can do it from (https://github.com/oncesk/yii-node-socket/tree/2.0.0)

####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 http://nodejs.org/
Install extension

  • Composer
composer require ratacibernetica/yii2-node-socket
  • Using git clone
$> git clone https://github.com/ratacibernetica/yii2-node-socket.git

Now go to the folder where you install extension vendors/ratacibernetica/yii2-node-socket and execute

$> git submodule init
$> git submodule update

Yii2 configuration

  • Configure console command in (console/config/main.php). You can use config below:
	...
	'controllerMap' => [
		'node-socket' => '\YiiNodeSocket\NodeSocketCommand',
	],
	...
	'components' => [
		'nodeSocket' => [
		    'class' => '\YiiNodeSocket\NodeSocket',
		    'host' => 'localhost',
		    'allowedServerAddresses' => [
		        "localhost",
		        "127.0.0.1"
		    ],
		],
	],
  • Register Yii component, need to add into frontend/config/main.php in your frontend application:
		'nodeSocket' => [
		    'class' => '\YiiNodeSocket\NodeSocket',
		    'dbOptions' => '',
		    '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/ratacibernetica/yii2-node-socket/lib/php',
        '@nodeWeb' => '@vendor/ratacibernetica/yii2-node-socket/lib/js',
        '@console'=>dirname(dirname(__DIR__)) . '/console',
    ],   

Notice: if you will be using 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

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

Notice: It's highly probable that the JS don't load by itself, so we must register the YiiSocketNode Assets in the view/layout.

use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use kartik\form\ActiveForm;
use frontend\assets\AppAsset;
use kartik\widgets\AlertBlock;

/* @var $this \yii\web\View */
/* @var $content string */


\YiiNodeSocket\Assets\NodeSocketAssets::register($this);
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
...

Like so.

###Console command actions (as administrative user)

Use (./yii node-socket/)

$> ./yii node-socket/start # start server
$> ./yii node-socket/stop # stop server
$> ./yii node-socket/restart # restart server
$> ./yii node-socket/get-pid # 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.

###About Yii2's User model

We need to follow these steps to send events to certain Users:

    
/**
* This is the model class for table "usuer".
*/
    ...
    const EVENT_BEFORE_LOGIN = 'beforeLogin';
    const EVENT_BEFORE_LOGOUT = 'beforeLogout';
    const EVENT_AFTER_LOGIN = 'afterLogin';
    ...
    /**
     * Crea un único Frame para autorizar al usuario
     * y recibir notificaciones exclusivas para él.
     * @param type $fromCookie
     */
    protected function afterLogin($fromCookie) {
        $frame = \Yii::$app->nodeSocket->getFrameFactory()->createAuthenticationFrame();
        $frame->setUserId(\Yii::$app->user->id);
        $frame->send();
    }

    public function beforeLogin() {
        
    }

    public function beforeLogout() {
        
    }

####Register these Events

As Yii2 doesnt have those events anymore, we need to add them.

So i created a file named "AppBootstrap":

<?php
namespace frontend\bootstraps;
use yii\base\BootstrapInterface;

 class AppBootstrap implements BootstrapInterface{

   public function bootstrap($app){
      $app->user->on(\common\models\Usuario::EVENT_BEFORE_LOGIN,['common\models\Usuario', 'beforeLogin']);
      $app->user->on(\common\models\Usuario::EVENT_AFTER_LOGIN,['common\models\Usuario', 'afterLogin']);
      $app->user->on(\common\models\Usuario::EVENT_BEFORE_LOGOUT,['common\models\Usuario', 'beforeLogout']);
   }
}

And add it, indeed, to frontend/config/main.php

'bootstrap' => ['log','nodeSocket','frontend\bootstraps\AppBootstrap'],

So, we just subscribed the logged user to node's service (or something like that, not sure).

###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
  • clients in concrete room

Global events:

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

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 => 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 :)