PHP code example of ratacibernetica / yii2-node-socket

1. Go to this page and download the library: Download ratacibernetica/yii2-node-socket library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ratacibernetica / yii2-node-socket example snippets


	...
	'controllerMap' => [
		'node-socket' => '\YiiNodeSocket\NodeSocketCommand',
	],
	...
	'components' => [
		'nodeSocket' => [
		    'class' => '\YiiNodeSocket\NodeSocket',
		    'host' => 'localhost',
		    'allowedServerAddresses' => [
		        "localhost",
		        "127.0.0.1"
		    ],
		],
	],

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


    'aliases' => [
        '@YiiNodeSocket' => '@vendor/ratacibernetica/yii2-node-socket/lib/php',
        '@nodeWeb' => '@vendor/ratacibernetica/yii2-node-socket/lib/js',
        '@console'=>dirname(dirname(__DIR__)) . '/console',
    ],   


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



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);

    
/**
* 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() {
        
    }


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']);
   }
}

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


/**
 *
 * @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



protected function afterLogin($fromCookie) {
	parent::afterLogin($fromCookie);
	
	$frame = Yii::app()->nodeSocket->getFrameFactory()->createAuthenticationFrame();
	$frame->setUserId($this->getId());
	$frame->send();
}




// $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();


public function actionIndex() {
	...

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


...

// 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();

...



...

// 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();

...



...

// 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();

...



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



...

$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
	}
}

...



$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();



$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();