


Introduction to the combination of GatewayWorker and ThinkPHP and other frameworks
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 steps1.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
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
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
<?php use \GatewayWorker\Lib\Gateway;class Events { // 当有客户端连接时,将client_id返回,让mvc框架判断当前uid并执行绑定 public static function onConnect($client_id) { Gateway::sendToClient($client_id, json_encode(array( 'type' => 'init', 'client_id' => $client_id ))); } // GatewayWorker建议不做任何业务逻辑,onMessage留空即可 public static function onMessage($client_id, $message) { } }
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 || ''; switch(type){ // Events.php中返回的init类型的消息,将client_id发给后台进行uid绑定 case 'init': // 利用jquery发起ajax请求,将client_id发给后端进行uid绑定 $.post('./bind.php', {client_id: data.client_id}, function(data){}, 'json'); break; // 当mvc框架调用GatewayClient发消息时直接alert出来 default : alert(e.data); } };mvc backend uid binding code fragmentbind.php (using GatewayClient binding)
<?php//加载GatewayClient。关于GatewayClient参见本页面底部介绍require_once '/your/path/GatewayClient/Gateway.php';// GatewayClient 3.0.0版本开始要使用命名空间use GatewayClient\Gateway;// 设置GatewayWorker服务的Register服务ip和端口,请根据实际情况改成实际值(ip不能是0.0.0.0)
Gateway::$registerAddress = '127.0.0.1:1236';// 假设用户已经登录,用户uid和群组id在session中
$uid = $_SESSION['uid'];
$group_id = $_SESSION['group'];// client_id与uid绑定
Gateway::bindUid($client_id, $uid);// 加入某个群组(可调用多次加入多个群组)
Gateway::joinGroup($client_id, $group_id);
mvc backend message code snippet
###send_message.php (sent using GatewayClient)###<?php//加载GatewayClient。关于GatewayClient参见本页面底部介绍require_once '/your/path/GatewayClient/Gateway.php';// GatewayClient 3.0.0版本开始要使用命名空间use GatewayClient\Gateway;// 设置GatewayWorker服务的Register服务ip和端口,请根据实际情况改成实际值(ip不能是0.0.0.0) Gateway::$registerAddress = '127.0.0.1:1236';// 向任意uid的网站页面发送数据 Gateway::sendToUid($uid, $message);// 向任意群组的网站页面发送数据 Gateway::sendToGroup($group, $message);
注意
以上仅是mvc框架与GatewayWorker官方推荐的结合方式,并不是强制使用此方式,开发者可以自由变化选择结合方式以适应自己的业务需求。
当然也可以采用客户端与GatewayWorker直接双向通讯的方式完成业务通讯。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
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!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version