PHPackages                             meshell/surf - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. meshell/surf

ActiveFramework[Framework](/categories/framework)

meshell/surf
============

v1.1.2(7y ago)327MITPHPPHP &gt;=7

Since Apr 10Pushed 7y ago1 watchersCompare

[ Source](https://github.com/TianLiangZhou/surf)[ Packagist](https://packagist.org/packages/meshell/surf)[ RSS](/packages/meshell-surf/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (7)Dependencies (9)Versions (16)Used By (0)

Surf
====

[](#surf)

[![Build Status](https://camo.githubusercontent.com/1afa5a145e2fa14f5526c066a904b166c02a82cf3d02164cd10dad33b91600c4/68747470733a2f2f7472617669732d63692e6f72672f5469616e4c69616e675a686f752f737572662e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/TianLiangZhou/surf)[![License](https://camo.githubusercontent.com/5e25f857ea70d6e61023befad1d4195a9196c47ce3e73e4ef77a0d8e2e2e98f3/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d6d69742d626c75652e737667)](LICENSE)[![Coverage Status](https://camo.githubusercontent.com/c8ca802591da9f8f2ab3f37898bc12be0064ed750593f3a49e29a24c8ead7dfb/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f5469616e4c69616e675a686f752f737572662f62616467652e7376673f6272616e63683d253238484541442b64657461636865642b61742b61623535633465253239)](https://coveralls.io/github/TianLiangZhou/surf?branch=%28HEAD+detached+at+ab55c4e%29)[![Maintainability](https://camo.githubusercontent.com/c363eef013ae3563a8aed9ac2090fe99b2de639b49c2944be7318a8030e68088/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f35633439323230346466636634313537666338622f6d61696e7461696e6162696c697479)](https://codeclimate.com/github/TianLiangZhou/surf/maintainability)

`surf` 是一个对[`Swoole`](https://github.com/swoole/swoole-src)扩展库的封装，它可以像传统`MVC`一样编写 **Http**,**Tcp** 应用.

Installation
------------

[](#installation)

使用[Composer](https://getcomposer.org/)来安装框架.

```
$ composer require meshell/surf "^1.0.5"
```

Usage
-----

[](#usage)

一个简单的`http`应用，创建一个配置文件`config.php`.

```
# config.php

return [
    'host' => '0.0.0.0',
    'port' => 9527,
    'setting' => [
        'reactor_num' => 8,
        'worker_num' => 10,
    ]
];
```

创建一个`http.php`文件.

```
require __DIR__ . '/vendor/autoload.php';

$app = new \Surf\Application(__DIR__, [
    'app.config' => __DIR__ . '/config.php'
]);

$app->addGet('/', function() {
    return "Hello world";
});
$app->register(new \Surf\Provider\PoolServiceProvider());
$app->run();
```

启动服务.

```
$ php http.php
```

浏览器打开 显示 "Hello world", 你也可以使用`curl`.

```
$ curl http://127.0.0.1:9527/
```

查看事例[http](examples/http/http.php)

一个简单的`tcp`应用, 配置文件还是使用上面的`config.php`, 创建一个`tcp.php`. `tcp`需要设置`protocol`解析类. 一般`tcp`服务端和客户端使需要约定消息格式才能解析出正确的数据. 在`surf`中我们使用的默认解析格式是包头，包长，包体(`unpack(A64header/Nlen/A*data)`)作为消息格式。调用每条协议我们是定义在`包头`中.

```
include __DIR__ . '/vendor/autoload.php';

$config = include __DIR__ . '/config.php';

$config['server'] = 'tcp';
$config['protocol'] = \Surf\Server\Tcp\Protocol\JsonProtocol::class;

$app = new \Surf\Application(__DIR__, [
    'app.config' => $config
]);
$app->addProtocol('user.name', Examples\TestTcpController::class . ':name');
$app->run();
```

编写客户端程序`client.php`.

```
$client = new Swoole\Client(SWOOLE_SOCK_TCP);

if (!$client->connect('127.0.0.1', 9527, -1)) {
    exit("connection failed");
}

$message = json_encode([
    'name' => 'meShell',
    'age'  => 18,
    'job' => 'engineer'
]);
$hex = pack('A64NA*', "name=user.name;format=json", strlen($message), $message);

$client->send($hex);

echo $client->recv();

$client->close();
```

启动服务

```
$ php tcp.php
```

连接服务

```
$ php client.php
```

打印服务返回内容: "my name is meShell, my age is 18, My job is an engineer";

查看事例[tcp](examples/tcp/tcp.php)

#### Connection pool

[](#connection-pool)

在`surf`中使用连接池功能.

```
#config.php
return [
    ...
    'database' => [
        'default' => [
            'driver' => 'mysql',
            'host'   => 'localhost',
            'database' => 'test',
            'username' => 'root',
            'password' => "123456",
            'options'  => [],
        ],
    ],
    'cache' => [
        'default' => [
            'driver' => 'redis',
            'host'   => '127.0.0.1',
            'port'   => 6379,
            // 'prefix' => 'SURF:'
            // 'auth' => 'password'
        ],
    ],
    'pool' => [
        'interval' => 100, //心跳检测时间，以毫秒为单位
        'database' => [
            'default' => [
                'start_number' => 10 //默认开启
            ],
        ],
        'cache' => [
            'default' => [
                'start_number' => 10 //默认开启
            ],
        ],
    ],
];
```

在启动文件里注册`provider`.

```
$app->register(new \Surf\Provider\PoolServiceProvider());
```

在`Controller`中获取连接池中的对象.

```
/**
* @var $pool PoolManager
*/
$pool = $this->container->get('pool'); //获取连接池管理对象
/**
* @var $pdo \Surf\Pool\Connection 获取一个数据库对象
*/
$pdo  = $pool->pop('database.default'); //从database.default池子中获取当前对象

/**
* 获取一个缓存对象 需要注册
* $app->register(new \Surf\Provider\CacheServiceProvider());
*/
$redis = $pool->pop('cache.default'); //从cache.default池子中获取当前对象
```

查看事例[pool](examples/TestController.php)

#### Usage `Session` and `Cookie`

[](#usage-session-and-cookie)

`session` 和 `cookie` 在`web`开发中是经常需要使用的保存一些登录信息, 登录状态等等.

在`匿名函数`中使用. 在回调函数时候框架会自动将`路由变量`, `request`, `cookies` 这几个参数填充到函数.

```
use Surf\Server\Http\Cookie\CookieAttributes;

$app->addGet('/', function($routeVars, Request $request, Cookies $cookies) {

    $session = $request->session; //获取session 对象
    $session->set('userInfo', ['id' => 1]);
    //使用cookie, 传入一个CookieAttributes对象
    $cookies->set(CookieAttributes::create('name', 'value', 0));
});
```

在`HttpController`中使用.

```
use Surf\Server\Http\Cookie\CookieAttributes;

$app->addGet('/', 'SessionController:index');

...

class SessionController extends HttpController
{
    ...

    public function index($routeVars)
    {
        $session = $this->request->session; // or $this->session; 获取session 对象
        $session->set('userInfo', ['id' => 1]);
        //使用cookie
        $this->cookies->set(CookieAttributes::create('name', 'value', 0));
    }
}
```

查看事例[session](examples/session/session.php)

#### 任务

[](#任务)

在控制器中使用`$this->task()`, 这个是异步, 想使用同步可以`$this->syncTask()`.

```
    ...
    public function taskTest()
    {
        $taskId = $this->task('push all message worker' . $this->workerId, PushTaskHandle::class);
        //$status = $this->syncTask('sync push all message', PushTaskHandle::class);
        //var_dump($status);
        return "task push id:" . $taskId . ", workId:" . $this->workerId;
    }
```

查看事例[task](examples/task/task.php)

#### 全局定时器

[](#全局定时器)

在有些业务中我们可能会有这样的需求，比如每隔两小时需要读取下订单数.但你也可以用`crontab`实现. 相同时间的定时器会被最后一次添加的定时器覆盖,定时器时间单位为毫秒.

```
...

$app->addTicker(100, \Surf\Examples\HeartbeatTicker::class);

try {
    $app->run();
} catch (\Surf\Exception\ServerNotFoundException $e) {

}
```

查看事例[ticker](examples/ticker/ticker.php)

License
-------

[](#license)

[LICENSE](LICENSE)

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~11 days

Recently: every ~20 days

Total

13

Last Release

2824d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5e2c43e0e3b8fa7a494596ed91e3bca44f63079e61196a01288535c326185383?d=identicon)[TianLiangZhou](/maintainers/TianLiangZhou)

---

Top Contributors

[![TianLiangZhou](https://avatars.githubusercontent.com/u/7042876?v=4)](https://github.com/TianLiangZhou "TianLiangZhou (5 commits)")

---

Tags

micro-frameworkmicro-swoole-apimicro-swoole-frameworkmvcmvc-frameworkswoole-frameworkframeworkmicroswoole-frameworkmicro-swoole-frameworkmicro-swoole-api

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/meshell-surf/health.svg)

```
[![Health](https://phpackages.com/badges/meshell-surf/health.svg)](https://phpackages.com/packages/meshell-surf)
```

###  Alternatives

[slim/slim

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs

12.2k49.9M1.3k](/packages/slim-slim)[clue/framework-x

Framework X – the simple and fast micro framework for building reactive web applications that run anywhere.

936736.7k8](/packages/clue-framework-x)[vlucas/bulletphp

A heierarchical resource-oriented micro-framework built on nested closures instead of route-based callbacks

41949.9k1](/packages/vlucas-bulletphp)[gnugat/micro-framework-bundle

Symfony Micro Framework Bundle

3710.6k1](/packages/gnugat-micro-framework-bundle)[linio/tortilla

A highly opinionated microframework built with speed and simplicity in mind.

133.0k2](/packages/linio-tortilla)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
