仿 swoole 初始化回调实现

Swoole:面向生产环境的 PHP 异步网络通信引。

是PHPer进阶的必备技能,但是像我这种初学者,对于 PHP 面向对象了解不深的人,Swoole 的官方文档一下就看懵了。所以,我花了一些时间,写了一个 Swoole 的初始化回调,来学习 PHP 的更高级的用法(高级:是相对于只知道 CRUD 来说)。

*本文只涉及面向对象的回调实现!!!!!!

*本文代码只是猜想,并不是源码分析!!!!!!

官方示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$http = new swoole_http_server("127.0.0.1", 9501);

$http->on("start", function ($server) {
echo "Swoole http server is started at http://127.0.0.1:9501\n";
});

$http->on("request", function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello World\n");
});

$http->start();

01 问题

调用 $http->on(); 之后,有两个参数,一个参数是字符串,一个是回调函数,这两个参数都可以立即。理解不了的是第二个参数也就是匿名函数中的参数,我们并没有指定。那么是谁帮我们指定的?

02 相关资料

PHP回调函数

03 思路

其实思路就是在 swoole_http_server 中,有个 on 方法。on 方法主要实现为,根据第一个参数来实例化,相应的对象并回调第二个参数,同时,将实例化的对象作为参数传递给回调函数。

04 代码实现

先实现 swoole_http_server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php 


class swoole_http_server
{
public function on ($event, $callback)
{
return call_user_func_array([$this, $event], [$callback]);
}

//这里只实现 request,因为它有两个参数。
public function request($callback)
{
$request = new Request();
$response = new Response();
call_user_func($callback, $request, $response);
}

}

Request 类

1
2
3
4
5
6
7
8
9
<?php
class Request
{
public function header($title)
{
echo $title.PHP_EOL;
}

}

Response 类

1
2
3
4
5
6
7
8
9
<?php 
class Response
{
public function end($str)
{
echo $str.PHP_EOL;
}

}

调用

1
2
3
4
5
6
7
8
<?php 
//调用
$httpServer = new swoole_http_server();

$httpServer->on('request', function ($request, $response) {
$request->header('设置了一个title'); //输出 设置了一个title
$response->end('这里就结束了!!'); //输出 这里就结束了!!
});

05 总结

这是我第一次写博客,可能有很多没有写明白的地方,欢迎各路大神拍砖。

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~