Web 服务器

优质
小牛编辑
116浏览
2023-12-01

Swoole框架提供的WebServer有3种使用方法

一、直接使用HttpServer

HttpServer支持静态文件和include file。业务代码不需要写任何Server的代码,只需要设置document_root,并编写对应php文件。这种使用方法与Apache/Nginx+FPM类似。

server.php

$AppSvr = new Swoole\Network\Protocol\HttpServer();
$AppSvr->loadSetting("./swoole.ini"); //加载配置文件
$AppSvr->setDocumentRoot(__DIR__.'/webdocs/'); //设置document_root

$server = new \Swoole\Network\Server('0.0.0.0', 9501);
$server->setProtocol($AppSvr);
//$server->daemonize(); //作为守护进程
$server->run(array('worker_num' => 2, 'max_request' => 1000));

webdocs/index.php

<?php
echo "hello world";

在浏览器中打开http://localhost:9501/index.php

二、继承HttpServer

业务代码只需要继承此类,并自行实现onRequest方法即可。

    /**
     * 处理请求
     * @param $request
     * @return Swoole\Response
     */
    function onRequest(Swoole\Request $request)

onRequest方法参数为解析好的Request对象

  • $request->post : $_POST
  • $request->get : $_GET
  • $request->cookie : $_COOKIES
  • $request->file $_FILES

onRequest方法必须返回一个Response对象

  • $response->body 返回的HTML内容
  • $response->head HTTP头信息

三、使用AppServer

基于AppServer类开发,就必须遵循Swoole MVC规范。具体可以查看examples/和apps/中的示例程序。 apps/目录中存放应用代码。

目录说明
apps/controllers控制器代码
apps/models数据模型代码
apps/teamplets模板文件
apps/config配置文件