Une introduction à Swoft, un PHP microservices co-routine framework basé sur l'extension Swoole. On verra les principaux fonctionnalités de Swoft, les advantages, inconvenient et applications possibles
Présentation datant de 2020
2. 2
Vanessa V.CHELLEN
• 15 ans d’expérience dans le web
• Directeur technique Extension Interactive
• Analyse et conception technique
• Spécialiste PHP
• Conception et développement spécifique sous Symfony, Sylius,
Sulu
• Développement sous Drupal, Prestashop et Wordpress
• Veille permanente sur l'ensemble des métiers du web
• Conférencier
• Créateur de « Drupal Mauritius » et « Symfony.mu »
5. 5
Swoft is a PHP microservices coroutine framework
based on the Swoole extension.
8. 8
Event-driven asynchronous &
coroutine-based concurrency
networking communication
engine with high performance
written in C and C++ for PHP
Supports built-in coroutine
with high availability, and you
can use fully synchronized
code to implement
asynchronous performance.
9. 9
MySQL - Concurrency 10K
requests to read data from
MySQL takes only 0.2s!
Mixed server - You can create
multiple services on the single
event loop: TCP, HTTP,
Websocket and HTTP2, and
easily handle thousands of
requests.
10. 10
The power of swoole lies in the
design of its process model,
which solves both the
asynchronous problem and the
parallelism.
15. Typical Swoft App
Console application
Http service (similar to the traditional framework)
Websocket service
Rpc service
Tcp service
swoft-cloud/swoft is a complete application demo
17. 17
Annotation
First Swoole-based annotation
framework.
Simple and flexible.
Annotations available to
quickly configure object
instances (Beans), register
routes, listen for events, etc.
Everything is automatic
Easily get the needed objects
from the container and use
them.
19. 19
Dependency injection (DI)
Control inversion (IOC)
Dependency Injection
For example, class A depends
on class B. Class B will be
injected into Class A by IoC.
At the heart of the Swoft
framework
Interface injection
¬ Annotation injection ( @Inject() ,
@Primary() )
¬ Configuration Injection
23. Aspect Oriented Programming (AOP)
AOP is an object oriented programming that makes it easier to decouple
business code, improve code quality, and increase code reusability.
Just a programming idea like OOP.
It can more easily decouple business code, improve code quality, and
increase code reusability.
The main function of AOP is to add new functions to the original
functions without invading the original function code.
OOP can only perform vertical abstract encapsulation, which can not
solve horizontal repetitive problems well, while AOP This problem is
solved very well.
26. Aspect Oriented Programming (AOP)
Key component of Swoft Framework
The AOP module of the Swoft framework provides a face-oriented
programming implementation that allows you to define method
interceptors and pointcuts to cleanly separate code that implements
functions that should be separated.
The idea of AOP is to cut out repetitive related functions horizontally and
then weave them in at the appropriate time, as shown in the figure.
AOP only intercepts public and protected methods and does not
intercept private methods.
27. Aspect Oriented Programming (AOP)
Advice
¬ It is the function you want, the function that is implemented by the method, that is,
the security, transaction, log, etc.
Connection point (JoinPoint)
¬ It is the place where you can place the advice. The basics of each method are before
and after (both of them are OK), or when the exception is thrown
Pointcut
¬ This is the specific method to define the cut
Aspect
¬ It is a combination of advice and pointcut.
28. Aspect Oriented Programming (AOP)
Target
¬ The target class mentioned in the introduction, that is, the object to be notified, that
is, the real business logic, can be woven into the face without knowing it.
Proxy
¬ The whole set of AOP mechanisms is through the proxy, and Swoft uses the PHP-
Parse class library to implement AOP more conveniently.
Weaving
¬ Weaving is the process of linking aspects with other objects to create an advised
object.
31. RPC
The framework encapsulates a set of high-performance RPC services.
Each RPC call can be used like a local function.
The service rules through interfaces, completely obscuring the
implementation details, greatly improving development efficiency and
reducing maintenance costs.
The RPC protocol can be implemented based on TCP, UDP or HTTP, but
TCP is more recommended
The main role of RPC is for service calls.
32. 32
RPC
Swoft provides us with the
underlying services of RPC, we
don't need to care about the
underlying communication
details and the calling process.
Swoft implements the interface
by defining an interface and
starts the RPC Server to provide
interface services. We only need
to write a few classes to
implement a simple RPC module
Annotation @Service.
33. 33
Http Service
Based on the SwooleHttp
Server implementation of the
coroutine HTTP service, the
framework layer is well
encapsulated, users can write
code according to the traditional
MVC way, you can get the ultra-
high performance brought by the
coroutine.
34. Http Service
Installation
composer require swoft/http-server
Features
PSR-7-based HTTP message implementation
Middleware based on PSR-15
@Controller flexible controller annotation
@RequestMapping flexible routing annotation
Client & Middleware
35. 35
Websocket service
The WebSocket service is
based on further
encapsulation on the existing
swoole ws server.
Installation
composer require swoft/websocket-
server
36. 36
Websocket service
Features
¬ Quick setup using websocket
server
¬ Support full custom process
processing if you don't want to use
the processing that comes with the
framework
¬ Support data parsing and routing
scheduling in the message phase
¬ General messaging method
package (send, sendToSome,
sendToAll, broadcast, etc.)
38. TCP Service
As from
2.0.4
release
Based on
the original
swoole
server
Installation
• composer
require
swoft/tcp-
server
Host, port &
configs are
completely
customizabl
e.
39. TCP Service
Swoft-based annotation system
Provide uniform protocol settings, support both EOF and length
Complete data transceiving and parsing, unified context/request and
response object encapsulation
Built-in request scheduling processing, you can distribute request data to
different methods like http.
Built-in supports a variety of packaging methods ( json php token ) and
can be freely extended.
41. 41
Database
Highly compatible with Laravel
ORM
Connect to the database using
native PDO
Redis can be accessed by using
the phpRedis Driver
Swoft uses the magic method
to pass commands to the
Redis server
42. 42
Microservice
A set of components for
developers to quickly build
microservices.
Service registration and
discovery
Fuse
Limiting
Configuration center
43. Other Features
PSR-7-based HTTP
message
implementation
PSR-11-based
container specification
implementation
PSR-14 based event
manager
Middleware based on
PSR-15
PSR-16 based cache
design
RESTful support
Internationalization
(i18n) support
Fast and flexible
parameter validator
Complete service
governance, fusing,
downgrading, loading,
registration and
discovery
Coroutine,
asynchronous task
delivery
Custom user process
Powerful logging
system
45. Swoft CLI
The Swoft CLI is
a standalone
command line
application
package that
provides built-in
tools for
developers to
use.
Generate Swoft
application class
files, such as:
http controller,
websocket
module class,
etc.
Monitor file
changes for
user swoft
projects and
automatically
restart the
server
Quickly create
new app
projects or new
components
Package a swoft
app into a phar
package
46. Developers Tool
Swoft provides some built-in tools for developers to use.
Most of the tools are placed in the component
swoft/devtool
Installation
• composer require swoft/devtool
47. Developers Tool
CLI help
command
Operating
environment
check
Provide database
table entity class
generation
Provide basic
class template file
generation
Convenient web
UI
Server,
application
information
display
Registered
routing
information (http,
websocket, rpc)
Simple webSocket
test tool
Simple log view
(TODO)
Web version of
class file
generation
(TODO)
49. No you can’t
Forbidden die (), exit () function
Do not use super-global variables such as $_GET, $_POST, $GLOBALS,
$_SERVER, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV, etc.
Be cautious with Memory Leak
Use the global, static keyword with caution
Unable to do intensive calculations. Of course this is a problem with php
and even all dynamic languages.
51. What’s in for you ?
Developed in a componentized way, developers can customize and load
on demand.
The framework is a well-designed Web MVC framework that provides a
good choice for web frameworks.
To make it easier for PHP developers to get started, the use of databases
and caches is highly compatible with Laravel.
All components are strictly combined with unit testing and stress testing
#3:Dans la lignee de mon talk de l’annee derneire.. Le principe est de trouver des applications/fonctionnalites peu connu de PHP et les mettre de l’avant.
#6:Microservices are an architectural design
What microservices do is split the service according to the granularity of the project, and take the modules separately to make each individual small project
Technology stack, each service can be developed by different teams or developers,
Partial modification,
#7:ultra-lightweight threads, and you can easily create thousands of coroutines in a single process. Stop Resume Knows its state
The idea is that you don't just switch the tasks really fast to make it look like you are doing everything at once. You utilize the time you are waiting for something to happen(IO) to do other things that do require your direct attention. Manga – intro – faire un cafer –
Coroutines are "collaborative". Even in multi-core system, there is only one coroutine running at any given time (but multiple threads can run in parallel). Asynchronous
#9:Swoole v4.1.0, we added the ability to transform synchronous PHP network libraries into co-routine libraries using a single line of code
How many things you can do in 1s?
Sleep 10K times, read, write, check and delete files 10K times, use PDO and MySQLi to communicate with the database 10K times, create a TCP server and multiple clients to communicate with each other 10K times, create a UDP server and multiple clients to communicate with each other 10K times... Everything works well in one process!
#10:Starting with version 4.0, Swoole offers a complete Coroutine + Channel feature that brings the full CSP programming model. The application layer can use fully synchronous programming, and the underlying layer automatically implements asynchronous IO.
Using resident memory mode avoids the initialization of each frame and saves performance overhead. The underlying 4.x uses automated coroutine conversion.
#11:L’anee derneire j’avais parlais d’asynchronous php en version vanilla.. Et cette annee on va voir qu’il ya des frameworks robuste qui existe qui nous permette de faire de l’asynchrone
#17:The annotations are heavily referenced to SpringBoot , simplified on top of it, designed to be more suitable for PHP development, and easier to use.
swoft will automatically scan and collect annotation information, automatically configure the corresponding classes, and create their instances in advance into the IOC container.
PHPStorm - PHP annotations plugin to write functional annotations just like writing code. It provides powerful smart tips and error prompt
You can run a Swoft application without having to configure too many things.
#18:Line 1 introduces an annotation class, like a normal class
Line 8 uses annotations, format @类名 , and some class names will have parameters, such as "a" this annotation.
#19:The technology that Swoft most agrees with is the dependency injection (DI) that controls inversion. This Control Inversion (IOC) is a general concept that can be expressed in many different ways. Dependency injection is just a concrete example of control reversal.
When writing complex PHP applications, the application classes should be as independent as possible from other PHP classes to increase the likelihood of reusing them and testing them independently of other classes during unit testing. Dependency injection helps to glue these classes together while keeping them separate.
In an actual business scenario, many situations require interface-oriented programming, and the object actually implemented by the interface needs to be injected according to the interface class name
@Primary
If an interface has multiple implementations, this tag is the object used to make the interface injection, and only one of the multiple implementation classes of the same interface can have this annotation tag, otherwise the startup will prompt an error.
Dependency injection can be done by passing arguments to the constructor or by post-constructing using setter methods.
#21:Relying on the Swoole framework's own connection pool, it can be used with simple configuration without any other cost.
Swoft has built-in connection pooling feature, which makes it very convenient for you to use database, redis. And in the use of a highly compatible community-famous framework Laravel. You don’t have to worry about connection usage, Swoft will automatically connect to db and reclaim the connection after use.
#25:The ability to span multiple points in an application is called crosscutting concerns, which are conceptually separated from the application's business logic. There are a variety of common good examples, including logging, declarative transactions, security, caching, and more.
The key unit of modularity in OOP is the class, and in AOP, the modular unit is the facet. DI helps you separate application objects from each other, and AOP helps you separate cross-cutting concerns from the objects they affect.
#26:One of Swoft's key components is the Aspect Oriented Programming (AOP) framework.
#27:Advice
You should first define the function with the method first, and then use it where you want to use it.
Connection point (JoinPoint)
Swoft only supports method-level connection points. . Just remember that the front and back of the method are the connection points.
Pointcut
Assume that there are 10 methods in a class, each method has multiple join points (JoinPoint), but you do not want to use notifications in all methods (weaving ), you only want to weave some of these methods, then use this pointcut to define the specific method.
Aspect
The notice explains what to do, and the entry point indicates where to do it. In general, the connection point is specified when the pointcut is specified. The connection point is written separately for the sake of better understanding.
#29:@PointBean
Le pointcut
@PointAnnotation
Define 注解类 entry points
@Before pre-notification, execute this method before the target method is executed
@After post notification, execute this method after the target method is executed
@AfterReturning returns notifications
@AfterThrowing exception notification, this method is executed when the target method execution throws an exception
@Around surround notification, this method is executed before and after the target method is executed
#30:RPC is a Remote Procedure Call. Through RPC, we can call methods on other machines just like calling local methods. Users will not feel the communication between the server and the server. RPC plays a considerable role in microservices. Of course, RPC is not a way of microservices. There are other ways to implement remote calls such as RESTful APIs. If you have used SOAP then you will feel very similar to using RPC, you can directly call methods on other machines.
#31:TCP supports long connections. It is not necessary to perform a three-way handshake every time when calling a service. RPC has a good advantage in terms of performance and network consumption.
The RESTful API is based on HTTP, which means that each call to the service requires a three-way handshake to establish communication before the call can be made. This wastes a lot of bandwidth resources when our concurrency is high.
Restful = easier for external and RPc internal ?
#34:The Http Client officially recommends using saber and Guzzle to no longer recreate the wheels.
#35:The WebSocket service is based on further encapsulation on the existing swoole ws server. That is, the web request can be processed while the websocket service is enabled.
#36:The WebSocket service is based on further encapsulation on the existing swoole ws server. That is, the web request can be processed while the websocket service is enabled.
#38:Starting with the swowt 2.0.4 release, a tcp server implementation is provided in the swoft package.
Based on the original swoole server, the function is encapsulated and refined.
Swoft-based annotation system, easy to use and fast
Even have an Event listener if you want to listening to whats happening inside swoft
#39:Starting with the swowt 2.0.4 release, a tcp server implementation is provided in the swoft package. Based on the original swoole server, the function is encapsulated and refined.
Swoft-based annotation system, easy to use and fast
#41:Swoft DB operations are highly compatible with Laravel ability to use native SQL , a smooth query constructor, and the Eloquent ORM to interact with the DB from now on, eliminating the complex object association model. Connect to the database using native PDO
Redis is an open source, advanced key-value pair storage database. Since it contains strings, hashes, lists, collections, and ordered collections of these data types, it is often referred to as a data structure server.
#46:CLI help command
A CLI help command is provided to allow the user to quickly generate some basic classes. The generated class file can be used with a little adjustment.
#47:CLI help command
A CLI help command is provided to allow the user to quickly generate some basic classes. The generated class file can be used with a little adjustment.
#49:Be careful when dealing with global variables and static variables. This kind of variables that are not cleaned by the GC will exist throughout the life cycle. If not handled properly, it is easy to consume all the memory. In the past php-fpm, the php code will be completely released after the execution of the memory.
#51:Unable to do intensive calculations. Of course this is a problem with php and even all dynamic languages.
It's easier to leak memory.