Swoole, the real PHP web development framework, do you really know? !

1. Introduction to Swoole Framework

Swoole is a very sophisticated PHP framework that effectively improves development efficiency. Swoole has a unified and unique global object, similar to the Java registration tree, and mounts some commonly used objects, such as databases, template engines, cache systems, log systems, event processing systems, etc. You can easily call functions and develop quickly. To use the swoole framework, you only need to configure a config.php file, and you only need to require config.php in other PHP files to call all the functions of the framework.

Swoole can easily replace the module drive mode through the configuration file. For example, database connection can be easily changed between Pdo MySQL MySQLi. Cache can use filecache, dbcache, or memcache. The log can use database log, system log or file log.

Code:

<?php  
require 'config.php';  
//自动加载模块  
$php->autoload('db','tpl','cache','log','event','upload');  
//数据库查询  
$res = $php->db->query('select * from test');  
$one = $res->fetch();  
$all = $res->fetchall();  
//日志  
$php->log->info('hello');  
//缓存  
$php->cache->get('cache_key');  
$hello = $php->cache->set('cache_key','me',1800);  
//模板  
$php->tpl->assign('hello',$hello);  
$php->tpl->display('index.html');  

Swoole provides a lot of library tools, form generation, input verification and filtering, login verification processing, JS generation, Ajax support, debugging tools, client operations, URL merge and split tools, etc.

In addition, network classes (TCP, UDP Server & Client of Block, Select, Event) are also provided, and some simple server protocol implementations (HTTP, Chat, FTP, SMTP, POP3, etc.) are also provided. There are also 2 js libraries, UI library and form validation.

Two, advanced applications

The Swoole framework also provides the MVC apps structure. Through the inheritance of contoller, the encapsulation of business logic is realized, the inheritance of model is realized, and the encapsulation of data operation is realized. The view layer uses the smarty template engine to realize the logic encapsulation of page display.

The Swoole framework provides powerful Model classes, with get, gets, set, sets, del, dels, put, which can easily add, delete, and modify the database. The gets interface also has the function of automatic paging.

Swoole's SQL encapsulation is very flexible. Its characteristic is that all SQL splicing uses arrays instead of object methods, so that database query parameters can be seamlessly integrated with PHP's $_GET, $_POST, $_SESSION, Cache, and Cookie .

Code:

<?php  
$model = createModel('TestModel');  
$gets['where'][] = 'id>1';  
$gets['order'] = 'id desc';  
$gets['limit'] = 10;  
$gets['where'][] = 'category=10';  
$gets['select'] = 'id,title,name'];  
$gets['leftjoin'].  
  
$data = $model->gets($gets);  

Swoole also has ORM database operation methods, you can refer to the development manual.

The Swoole MVC URL routing method is completed by a function provided by the user. The user function only needs to return which Method of which Controller is called. With the use of url rewrite, any URL scheme can be customized, such as /controller/action/, controller_action.do, controller/action.do, etc. Or use regular rules to specify URLs like Django.

Event

Swoole provides an event trigger system.

$ php->event->raise(‘sendsms’,$ mobile,$sms_content);

This is a cool design. If in the local test environment, you are configured to synchronize, then the handle function corresponding to the event will be executed after the raise is triggered for a period of time. If it is a server environment, it can be set to asynchronous, then raise will only deliver an event to the Queue server. Start a daemon in the background, get the event from the Queue server, and then use the handle function to process it.

Upload

Swoole can process the uploaded files uniformly and limit the upload size. When uploading a picture, the size of the picture can be compressed automatically to generate a thumbnail.

Three, deployment method and stress test

The Swoole framework can be deployed in a typical LAMP environment like normal PHP. It can also run in the Http Server mode provided by Swoole itself.

Normal LAMP mode, because each request contains more php files, it is best to install OPCode cache such as APC. Stress test, the same code, the running efficiency is slightly lower than thinkphp, but far surpassing CodeIgniter, almost twice more.

It is worth mentioning that Swoole, which runs in Server mode, has extremely powerful performance. It is nearly 8-14 times that under the same code Apache deployment environment. And the memory footprint is very small.

Code:

<?php  
require('config.php');  
define('SESSION_CACHE','file://localhost#sess');  
require(LIBPATH.'/function/cli.php');  
//Mime格式  
require(LIBPATH.'/data/mimes.php');  
$mime_types = array_flip($mimes);  
//静态文件许可  
$static_files = array_flip(array('static','templates','swoole_plugin','favicon.ico','robot.txt'));  
$static_access = array_flip(array('html','htm','jpg','gif','png','js','css'));  
//加载全部controller  
import_all_controller();  
  
$_SERVER['run_mode'] = 'server';  
$_SERVER['server_driver'] = 'SelectTCP'; //BlockTCP,EventTCP,SelectTCP  
$_SERVER['server_host'] = '0.0.0.0';  
$_SERVER['server_port'] = 8888;  
$_SERVER['server_processor_num'] = 4;   //启用的进程数目  
$_SERVER['session_cookie_life'] = 86400; //保存SESSION_ID的cookie存活时间  
$_SERVER['session_life'] = 1800;  
  
$php->runServer();  

Test code:

Php code

<?php  
class page extends Controller  
{
    
      
    function index()  
    {
    
      
        $data = createModel('UserInfo')->get(12)->get();  
        $this->swoole->tpl->assign('data',$data);  
        $html = $this->swoole->tpl->fetch('test.html');  
        $time = $this->showTime();  
        return $html.$time;  
    }  
}  

Shell code

ab -c 100 -n 1000 -k http://127.0.0.1:8888/page/index/  
  
Requests per second  
Time per request (mean)  
Time per request (mean, across all concurrent requests)  

Insert picture description here

Tested under my Ubuntu (Inter core E5300+2G memory, and there are other software running ecilpse, firefox, chrom). Apache only ran to more than 80 RPS. The 4-process Swoole Server actually ran to an amazing 1153RPS.

You can use apache ProxyPass or Nginx upstream for proxy distribution and load balancing.

Pay attention, don't get lost

Alright, everyone, the above is the entire content of this article. The people who can see here are all talents . As I said before, there are a lot of technical points in PHP, because there are too many, it is really impossible to write, and you will not read too much after writing it, so I will organize it into PDF and documents here, if necessary Can

Click to enter the secret code: PHP+「Platform」

Insert picture description here

Insert picture description here


For more learning content, please visit the [Comparative Standard Factory] excellent PHP architect tutorial catalog, as long as you can read it to ensure that the salary will rise a step (continuous update)

The above content hopes to help everyone . Many PHPers always encounter some problems and bottlenecks when they are advanced. There is no sense of direction when writing too much business code. I don’t know where to start to improve. I have compiled some information about this, including But not limited to: distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripts, Docker, microservices, Nginx, etc. Many knowledge points, advanced advanced dry goods, can be shared with everyone for free, and those who need can join my PHP technology exchange group

Guess you like

Origin blog.csdn.net/weixin_49163826/article/details/108830628