Light PHP high performance PHP framework based on swote


🚀Light-phpIt is a high-performance PHP framework based on swote. It has excellent performance in small and medium-sized high-performance projects because of its lightweight encapsulation and ease of use.


Environmental requirements

rely on explain
PHP >= 7.2 Recommendation 7.2
Swoole >= 4.2.9 PHP5 is no longer supported since 2.0.12 Recommendation 4.2.9+
Linux Most Linux systems can CentOS recommended

Installation tutorial

1-1ComposerInstallation(packagist)The version installed in this way may not be the latest. Please install in 1-2 mode if this problem occurs.

composer create-project woann/light-php -vvv


git clone

2. Rename.env.exampleThe document is.env, and configure

3. Execute under the project root directoryphp bin\light startStart service

4. Browser accesshttp:// can seehello worldThe output of. At this point, the framework is installed.

configuration file

1. The configuration file of light PHP is in the/configDirectory, the framework integrates the global environment configuration file/.envThe general configuration is configured in the. Env file.

2./config/app.phpThe main configuration file of the framework is mainly used for configurationswooleExpand the relevant parameters.

3./config/databases.php, database configuration file, which configures the parameters related to database connection.

4./config/hook.php, configure hooks (hooks are mainly used to separate business logic from notification services).

5./config/redis.php,redisConfiguration file, configuredredisConnect related parameters.

6./config/route.php, routing profile.

7. The specific parameter meanings of the above configuration files are annotated in the code, so we will not do more here


Here is an example of a route/config/route.php, including HTTP routing and websocket routing (Note: in routing, the controller parameter is the abbreviation of controller, and the actual controller file should be appended afterController)

return [
    'm '= >'index', // default module
    'C' = >'index ', // default controller
    'a' = >'init ', // default operation
    'ext' = > '. HTML', // pseudo static suffix such as. HTML
    'HTTP' = > [// HTTP route
        //Uri -- request method -- module / controller / method ----- [middleware]
        '/'     => ['GET','Index/Index/index','Test'],
        'test/'    => ['GET','Index/Index/ws']
    'websocket' = > [// websocket routing
        //Uri -- module / controller / method
        'ws' => 'Index/WebSocket/index',


Middleware files should be created in/app/MiddlewareDirectory, class name and file name to be consistent, and implementLib\MiddlewareInterface, middleware processing method name must behandleAfter filtering, if passed, the final return result must betrue。 Example:

namespace app\Middleware;

use Lib\Middleware;
class Test implements Middleware{
    public function handle($request)
        //The middleware judgment logic is handled here,

        //After the program finally passes the verification, it returns true;
        return true;


1. Create the controller. The controller file should be created in/app/ControllerDirectory, class name and file name must be consistent, must inheritLib\ControllerClass, example:

namespace app\Controllers\Index;

use Lib\Controller;

class IndexController extends Controller {
    //General output
    public function index()
        return 'hello world';
    //Output JSON
    public function index1()
        return $this->json(["code" => 200, "msg" => "success"]);
    //Call template
     public function index2()
        $a = "test";
        //Output under the directory / APP / resources / views index.blade.php Template with the parameter $a. Support template path with. Splicing (same as template engine in laravel)
        return $this->view("index",["a" => $a]);
        //You can also call the view function directly
        return view("admin.index",["a" => $a]);

2. Get parameters

//Get get parameters
    $this > request > get(); // get all get parameters: array
    $this > request > get ("name"); // pass the parameter string to get the parameter whose key is name: string
    $this > request > get (["name", "age")); // pass the parameter array to get the parameter whose key is name and age: array
    //Get post parameter
    $this > request > post(); // get all get parameters: array
    $this > request > post ("name"); // pass the parameter string and get the parameter whose key is name: string
    $this > request > post (["name", "age")); // pass the parameter array to get the parameter whose key is name and age: array
    //Get upload file
    $this > request > getfiles(); // get all
    $this > request > GetFile ("image"); // get the specified file
    //File upload
    //--------File - [path] (based on / resources / uploads /) - [new file name] (default is randomly generated)
    uploadFile($file,"banner"," test.png "); // the upload file method developers can also write the upload operation without using this method


1. Create a hook. The hook file should be created in/app/HookDirectory, class name and file name must be consistent, must inheritLib\BaseHookClass, example:

namespace app\Hook;

use Lib\BaseHook;
use Lib\Log;
class TestHook extends BaseHook {
    public function start($name,$ip,$port)
        //This hook is executed when the server starts
        Log:: getinstance() - > write ('info ', $name, "boot succeeded", "{$IP}: {$port}", "at", date ('y-m-d H: I: s'));
    public function open($server,$fd){
        //You can bind the user ID and FD after the websocket link is successful
    public function close($server,$fd){
        //The user ID and FD can be unbound after websocket closes the link

2. In the hook configuration file/app/config/hook.phpRegister hook in

return [
    'start'     => [
    'open'      => [
    'close'     => [

3. Use the hook

//--Get hook service instance -- listening method -- hook name --- parameter (...)------

Task task

1. Create a task class. The task file should be created in/app/TaskDirectory, the class name and file name should be consistent, example:

namespace app\Task;

class Notice{
     *Send messages to all online clients
     *@ param $FD
     *@ param $data what to send
     * @return bool
    public function ToAll($fd,$data){
        $FDS = []; // used to store all client FD
        foreach($this->server->connections as $client_fd){
            if($fd != $client_fd && $this->server->exist($client_fd)){
                //Circulates the message to the client, excluding the sender FD
                $fds[] = $client_fd;
        Return "a notification has been sent to [". Join (",", $FDS) "]. The content of the notification is." $data;

2. Post task in controller

//---------Get task example -- assign task server -------- post task --- task class -------- method -------- parameter


1. Open websocket server and configure it.envfileSERVER_TYPE=websocketIn this configuration environment, you can listen to HTTP at the same time

2. Define the route. Refer to the routing section of the document in the routing configuration file/config/route.phpwebsocketThe route is defined under the index.

3. Controller example

namespace app\Controllers\Index;

use Lib\WsController;
class WebSocketController extends WsController {
    public function index()
        //Send message to client
        //$this - > > FD client unique ID
        //$this - > > server websocket server object (refer to the swote document for the functions provided by this object)
        $data "hahaha, I'm a message";
        $data2: "this is a group message sent by task task task";
        //Post asynchronous task
        $this->task->delivery (\app\Task\Notice::class,'ToAll',[$this->fd,$data2]);


4. Front end skip (there is a ws.blade.php File, can be used to test websocket


The database adoptslaravelFramedIlluminate\DatabaseIf you are familiar with laravel, you can use it very quickly.

1. Query builder, refer tofile

namespace app\Controllers\Index;

use Lib\Controller;
use Lib\DB;
class IndexController extends Controller {

    public function index()
        $res = DB::table('user')->where('id',1)->first();

2. Model, referencefile

namespace app\Models;

use Illuminate\Database\Eloquent\Model;
class User extends Model
    protected $table = 'user';

Stress testing

  • Call a JSON output method in the framework, and output the following contents:
    "word": "hello world"

  • Method has a stress test for a query statement
 public function index(){
        $res = DB::table('user')->where('id',"=","1")->first();
        return $this->json($res);

Recommended Today

Summary of recent use of gin

Recently, a new project is developed by using gin. Some problems are encountered in the process. To sum up, as a note, I hope it can help you. Cross domain problems Middleware: func Cors() gin.HandlerFunc { return func(c *gin.Context) { //Here you can use * or the domain name you specify c.Header(“Access-Control-Allow-Origin”, “*”) //Allow header […]