search
HomeBackend DevelopmentPHP TutorialPHP 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 文件,根据需要调整相关环境配置

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

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
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');
    }
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
This article is reproduced at:php100. If there is any infringement, please contact admin@php.cn delete
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function