Home Backend Development PHP Tutorial PHP microservice coroutine framework Swoft

PHP microservice coroutine framework Swoft

Jun 17, 2020 pm 05:17 PM
php application

PHP microservice coroutine framework Swoft

Introduction

With powerful extensions like swoole, more and more frameworks are based on swoole Developed, Swoft is one of the good PHP frameworks. Swoft is an annotation framework based on Swoole's native coroutine. It comes with resident memory and encapsulation of other Swoole functions. There is a coroutine client built into swoft. At the same time, there are many new concepts in swoft, such as Aop and so on.

Official website address: https://www.swoft.org/

Precautions for using the Swoft framework

Because Swoft is based on Swoole, it is compatible with Ordinary PHP frameworks are still very different, and some need to be paid attention to.

 1. Do not execute sleep() and other sleep functions in the code, as this will cause the entire process to block.

 2. Do not use the exit/die function, which will cause the worker process to exit directly.

 3. Process isolation needs to be noted. When the value of a global variable is modified, it will not take effect because the memory space of global variables is isolated in different processes. Using the Swoft framework requires understanding of process isolation issues. PHP variables are not shared between different processes, even if they are global variables. If different processes need to share data, you can use tools such as Redis, Mysql, message queue, file, Swoole/Table, APCu (php's own cache extension), shmget (process communication (IPC) shared memory) and other tools. At the same time, the file handles of different processes are also isolated, so the files opened by the Socker connection created in process A are invalid in process B.

4. Process cloning. When the server starts, the main process will clone the current process state. From then on, the data in the process will be independent of each other and will not affect each other.

5. Don’t write a base class in the controller to write public variables. This will cause data pollution. When the next request comes in, this variable will still be requested. Because it is resident in memory and has simple interest, it will not be released. .

The official documentation also has hints

https://www.swoft.org/documents/v2/dev-guide/dev-note/

Swoft FrameworkInstallation

Installation environment requirements:

1. The gcc version is greater than or equal to 4.8.

  2. PHP version is greater than 7.1.

  3. Composer package management tool.

4. Install the Redis asynchronous client hiredis, which is already built-in after the latest version of Swoole4.2.6 and does not need to be installed.

  5. Swoole extension, this is necessary.

  6. Link the iterator dependent library pcre.

7. Swoole needs to enable coroutines and asynchronous redis.

Installation

git clone https://github.com/swoft-cloud/swoft
cd swoft
composer install
cp .env.example .env   #编辑 .env 文件,根据需要调整相关环境配置
Copy after login

If the following error occurs, it means that the redis extension is not available, because swoft requires the redis extension.

Of course it will be easier to use docker. Execute the following command

docker run -p 18306:18306 --name swoft swoft/swoft
Copy after login

Enter http:/ in the browser /127.0.0.1:18306 can open the Swoft local page.

Close and start the running command docker start/stop swoft

Swoft directory and file description

Enter the container to view the swoft directory

PHP microservice coroutine framework Swoft
root@880c142615c3:/var/www/swoft# tree -L 2
.
|-- CONTRIBUTING.md
|-- Dockerfile
|-- LICENSE
|-- README.md
|-- README.zh-CN.md
|-- app                        #应用目录
|   |-- Annotation        #定义注解相关目录|   |-- Application.php
|   |-- Aspect
|   |-- AutoLoader.php
|   |-- Common
|   |-- Console
|   |-- Exception
|   |-- Helper          #助手函数目录
|   |-- Http
|   |-- Listener         #事件监听器目录|   |-- Migration
|   |-- Model           #模型、逻辑等代码目录|   |-- Process
|   |-- Rpc            #RPC服务代码目录|   |-- Task            #任务投递管理目录,这里可以做异步任务或者定时器的工作
|   |-- Tcp
|   |-- Validator
|   |-- WebSocket         #WebSocket服务代码目录|   `-- bean.php
|-- bin
|   |-- bootstrap.php
|   `-- swoft            #Swoft入口文件|-- composer.cn.json
|-- composer.json
|-- composer.lock
|-- config
|   |-- base.php
|   |-- db.php
|   `-- dev
|-- database
|   |-- AutoLoader.php
|   `-- Migration
|-- dev.composer.json
|-- docker-compose.yml
|-- phpstan.neon.dist
|-- phpunit.xml
|-- public
|   |-- favicon.ico
|   `-- image
|-- resource                   #应用资源目录|   |-- language
|   `-- views
|-- runtime             #临时文件目录(日志、上传文件、文件缓存等)|   |-- logs
|   |-- sessions
|   |-- swoft.command
|   `-- swoft.pid
|-- test              #单元测试目录   
|   |-- apitest
|   |-- bootstrap.php
|   |-- run.php
|   |-- testing
|   `-- unit
`-- vendor
    |-- autoload.php
    |-- bin
    |-- composer
    |-- doctrine
    |-- monolog
    |-- myclabs
    |-- nikic
    |-- phar-io
    |-- php-di
    |-- phpdocumentor
    |-- phpoption
    |-- phpspec
    |-- phpunit
    |-- psr
    |-- sebastian
    |-- swoft
    |-- symfony
    |-- text
    |-- theseer
    |-- toolkit
    |-- vlucas
    `-- webmozart
Copy after login
PHP microservice coroutine framework Swoft

SwoftBean container

The Bean container is the core of Swoft. Each Bean is an instance of a class object. A container is a factory to store and manage Beans. When HttpServer starts, it will scan classes with @Bean annotations. Traditional PHP does not have resident memory. Each request will re-initialize various resources, and each object must be re-instantiated to apply for memory. After the request is processed, it will be consumed again, which is a waste of resources. Swoft will instantiate these objects and store them in memory after HttpServer is started. They will be taken out and used directly on the next request, reducing the consumption of object creation resources.

The bottom layer of the Bean container is a BeanFactory management container (Container).

Swoft Annotations Mechanism

Annotations are the basis for many important functions in Swoft, especially AOP and IoC containers. Friends who are familiar with Java should know more about annotations.

So what do annotations look like? The following is part of Swoft's code . has annotations in the comment section above the class, method or member variable.

PHP microservice coroutine framework Swoft
namespace App\Tcp\Controller;

use App\Tcp\Middleware\DemoMiddleware;
use Swoft\Tcp\Server\Annotation\Mapping\TcpController;
use Swoft\Tcp\Server\Annotation\Mapping\TcpMapping;
use Swoft\Tcp\Server\Request;
use Swoft\Tcp\Server\Response;
use function strrev;

/**
 * Class DemoController
 *
 * @TcpController(middlewares={DemoMiddleware::class})      #这个就是注解
 */
class DemoController
{
    /**
     * @TcpMapping("list", root=true)
     * @param Response $response
     */
    public function list(Response $response): void
    {
        $response->setData('[list]allow command: list, echo, demo.echo');
    }
Copy after login
PHP microservice coroutine framework Swoft

   注解是什么呢?有什么作用呢?

    注解其实是通过反射把注释当成代码的一部分,PHP可以通过ReflectionClass来获取一个类的信息,从而了解类里的信息,比如获取类中的所有方法、成员变量,并包括私有方法等,并根据这些信息实现一些操作。像很多PHP框架,比如laravel框架就利用PHP的反射机制来实现依赖注入。

    其实注解是配置的另一种方式,这里注解就可以起到一个配置作用。比如定义路由,定义配置定时任务,权限控制等。

    在Swoft中要是使用注解,需引入相关注解(Annotation)类,且必须以 /** 开始并以 */ 结束,否则会导致无法解析!

Aop切面编程

  Aop介绍

    1. Aspect(切面):通常是一个类,里面可以定义切入点和通知。

    2. JointPoint(连接点):程序执行过程中明确的点,一般是方法的调用。

    3. Advice(通知):Aop在特定的切入点执行的增强处理,有before,after,afterReturning,afterThrowing,around。

    4. Pointcut(切入点):就是嗲有通知的连接点,在程序中主要体现为书写切入点表达式。

        Swoft新版的Aop设计建立在PHP Parser上面。

    PHP-Parser的项目主页是:https://github.com/nikic/PHP-Parser

            推荐教程:《php教程

The above is the detailed content of PHP microservice coroutine framework Swoft. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP application: use current date as file name PHP application: use current date as file name Jun 20, 2023 am 09:33 AM

In PHP applications, we sometimes need to save or upload files using the current date as the file name. Although it is possible to enter the date manually, it is more convenient, faster and more accurate to use the current date as the file name. In PHP, we can use the date() function to get the current date. The usage method of this function is: date(format, timestamp); where format is the date format string, and timestamp is the timestamp representing the date and time. If this parameter is not passed, it will be used

Tutorial: Use Firebase Cloud Messaging to implement scheduled message push functions in PHP applications Tutorial: Use Firebase Cloud Messaging to implement scheduled message push functions in PHP applications Jul 25, 2023 am 11:21 AM

Tutorial: Using Firebase Cloud Messaging to implement scheduled message push functions in PHP applications Overview Firebase Cloud Messaging (FCM) is a free message push service provided by Google, which can help developers send real-time messages to Android, iOS and Web applications. This tutorial will lead you to use FCM to implement scheduled message push functions through PHP applications. Step 1: Create a Firebase project First, in F

Generic programming in PHP and its applications Generic programming in PHP and its applications Jun 22, 2023 pm 08:07 PM

1. What is generic programming? Generic programming refers to the implementation of a common data type in a programming language so that this data type can be applied to different data types, thereby achieving code reuse and efficiency. PHP is a dynamically typed language. It does not have a strong type mechanism like C++, Java and other languages, so it is not easy to implement generic programming in PHP. 2. Generic programming in PHP There are two ways to implement generic programming in PHP: using interfaces and using traits. Create an interface in PHP using an interface

Redis regular expression operation in PHP applications Redis regular expression operation in PHP applications May 16, 2023 pm 05:31 PM

Redis is a high-performance key-value storage system that supports a variety of data structures, including strings, hash tables, lists, sets, ordered sets, etc. At the same time, Redis also supports regular expression matching and replacement operations on string data, which makes it highly flexible and convenient in developing PHP applications. To use Redis for regular expression operations in PHP applications, you need to install the phpredis extension first. This extension provides a way to communicate with the Redis server.

Tutorial: Use Baidu Push extension to implement message push function in PHP application Tutorial: Use Baidu Push extension to implement message push function in PHP application Jul 26, 2023 am 09:25 AM

Tutorial: Use Baidu Cloud Push (BaiduPush) extension to implement message push function in PHP applications Introduction: With the rapid development of mobile applications, message push function is becoming more and more important in applications. In order to realize instant notification and message push functions, Baidu provides a powerful cloud push service, namely Baidu Cloud Push (BaiduPush). In this tutorial, we will learn how to use Baidu Cloud Push Extension (PHPSDK) to implement message push functionality in PHP applications. We will use Baidu Cloud

Signature authentication method and its application in PHP Signature authentication method and its application in PHP Aug 06, 2023 pm 07:05 PM

Signature Authentication Method and Application in PHP With the development of the Internet, the security of Web applications has become increasingly important. Signature authentication is a common security mechanism used to verify the legitimacy of requests and prevent unauthorized access. This article will introduce the signature authentication method and its application in PHP, and provide code examples. 1. What is signature authentication? Signature authentication is a verification mechanism based on keys and algorithms. The request parameters are encrypted to generate a unique signature value. The server then decrypts the request and verifies the signature using the same algorithm and key.

Redis operation log in PHP application Redis operation log in PHP application May 15, 2023 pm 08:10 PM

Redis operation logs in PHP applications In PHP applications, it has become more and more common to use Redis as a solution for caching or storing data. Redis is a high-performance key-value storage database that is fast, scalable, highly available, and has diverse data structures. When using Redis, in order to better understand the operation of the application and for data security, we need to have a Redis operation log. Redis operation log can record all clients on the Redis server

Application of PHP in enterprise-level website development Application of PHP in enterprise-level website development Oct 27, 2023 pm 06:52 PM

As one of the most popular server-side scripting languages, PHP is widely used in the development of enterprise-level websites. Its flexibility, scalability, and ease of use make PHP the language of choice for enterprise-level website development. This article will discuss the application of PHP in enterprise-level website development. First of all, PHP plays a key role in the development of enterprise-level websites. It can be used to build a variety of functions, including user authentication, data storage, data analysis, and report generation. PHP can be seamlessly integrated with databases and supports mainstream data

See all articles