Table of Contents
## Overall principles
Website page js fragment
注意
Home Backend Development PHP Tutorial Introduction to the combination of GatewayWorker and ThinkPHP and other frameworks

Introduction to the combination of GatewayWorker and ThinkPHP and other frameworks

Jul 05, 2018 pm 02:59 PM

This article mainly introduces the combination of GatewayWorker and ThinkPHP and other frameworks. It has certain reference value. Now I share it with you. Friends in need can refer to it.

Developers are most concerned about when using GatewayWorker The most important thing is how to integrate with the existing mvc framework (ThinkPHP Yii laravel, etc.). The following is the officially recommended integration method.

See diagram:

## Overall principles

Existingmvc framework projectWithGatewayWorkerIndependentDeployment does not interfere with each other

All business logic is completed from the website page post/get to the mvc framework

##GatewayWorker Does not accept data from the client, that is, GatewayWorkerdoes not process any business logic,GatewayWorker only serves as A one-way push channel

Only ifmvc frameworkNeedActively push data to the browserOnly in the mvc frameworkCall Gateway's API (GatewayClient)Complete the push

## Specific implementation steps

1.Website pageEstablishment andGatewayWorker#websocket connection

2. GatewayWorker found that a page initiated the connection When , send the client_id corresponding to the connection to the website page

3, Website page triggers an ajax request after receiving client_id (assuming it is bind.php)Send client_id to mvc backend

##4、mvc backend

bind.php After receiving client_id, use GatewayClient to call Gateway::bindUid($client_id, $uid)Bind client_id to the current uid (user id or client unique identifier). If there is a group or group sending function, you can also use Gateway::joinGroup($client_id, $group_id) to add client_id to the corresponding group

5. All requests initiated by the page are directly post/get to the mvc framework for unified processing, including sending messages

6. During the business process of the mvc framework

When you need to send data to a uid or a group, directly call the GatewayClient interface<span style="color: #ff0000;"><strong>Gateway::sendToUid<span style="text-decoration: underline;"><span style="color: #000000; text-decoration: underline;"> </span></span></strong>Gateway::sendToGroup<span style="text-decoration: underline; color: #000000;"><strong></strong></span></span> Wait for sending## Sample code

GatewayWorker fragment

Events.php code in GatewayWorker (only one onConnect callback setting)

<?php
use \GatewayWorker\Lib\Gateway;class Events
{    // 当有客户端连接时,将client_id返回,让mvc框架判断当前uid并执行绑定    public static function onConnect($client_id)
    {
        Gateway::sendToClient($client_id, json_encode(array(            &#39;type&#39;      => &#39;init&#39;,            &#39;client_id&#39; => $client_id
        )));
    }    // GatewayWorker建议不做任何业务逻辑,onMessage留空即可    public static function onMessage($client_id, $message)
    {

    }
}
Copy after login

Website page js fragment

/**
 * 与GatewayWorker建立websocket连接,域名和端口改为你实际的域名端口,
 * 其中端口为Gateway端口,即start_gateway.php指定的端口。
 * start_gateway.php 中需要指定websocket协议,像这样
 * $gateway = new Gateway(websocket://0.0.0.0:7272);
 */
ws = new WebSocket("ws://your_domain.com:7272");// 服务端主动推送消息时会触发这里的onmessage
ws.onmessage = function(e){    // json数据转换成js对象    var data = eval("("+e.data+")");    var type = data.type || &#39;&#39;;    switch(type){        // Events.php中返回的init类型的消息,将client_id发给后台进行uid绑定        case &#39;init&#39;:            // 利用jquery发起ajax请求,将client_id发给后端进行uid绑定
            $.post(&#39;./bind.php&#39;, {client_id: data.client_id}, function(data){}, &#39;json&#39;);            break;        // 当mvc框架调用GatewayClient发消息时直接alert出来        default :
            alert(e.data);
    }
};
Copy after login

mvc backend uid binding code fragment

bind.php (using GatewayClient binding)

<?php//加载GatewayClient。关于GatewayClient参见本页面底部介绍require_once &#39;/your/path/GatewayClient/Gateway.php&#39;;// GatewayClient 3.0.0版本开始要使用命名空间use GatewayClient\Gateway;// 设置GatewayWorker服务的Register服务ip和端口,请根据实际情况改成实际值(ip不能是0.0.0.0)
Gateway::$registerAddress = &#39;127.0.0.1:1236&#39;;// 假设用户已经登录,用户uid和群组id在session中
$uid      = $_SESSION[&#39;uid&#39;];
$group_id = $_SESSION[&#39;group&#39;];// client_id与uid绑定
Gateway::bindUid($client_id, $uid);// 加入某个群组(可调用多次加入多个群组)
Gateway::joinGroup($client_id, $group_id);
Copy after login

mvc backend message code snippet

###send_message.php (sent using GatewayClient)###
<?php//加载GatewayClient。关于GatewayClient参见本页面底部介绍require_once &#39;/your/path/GatewayClient/Gateway.php&#39;;// GatewayClient 3.0.0版本开始要使用命名空间use GatewayClient\Gateway;// 设置GatewayWorker服务的Register服务ip和端口,请根据实际情况改成实际值(ip不能是0.0.0.0)
Gateway::$registerAddress = &#39;127.0.0.1:1236&#39;;// 向任意uid的网站页面发送数据
Gateway::sendToUid($uid, $message);// 向任意群组的网站页面发送数据
Gateway::sendToGroup($group, $message);
Copy after login

注意

以上仅是mvc框架与GatewayWorker官方推荐的结合方式,并不是强制使用此方式,开发者可以自由变化选择结合方式以适应自己的业务需求。


当然也可以采用客户端与GatewayWorker直接双向通讯的方式完成业务通讯。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Yii1.1框架关于日志配置的使用

用laravel dingo api插件库创建api的方法

The above is the detailed content of Introduction to the combination of GatewayWorker and ThinkPHP and other frameworks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles