thinkphp5.1 workerman核心修改攻略

1、thinkphp原來的Response設(shè)置header方式不管用了,為什么正常開發(fā)的時(shí)候卻又好用?

\vendor\topthink\think-worker\src\Application.php的worker接管了Response?getContent解析,無論\application下如何業(yè)務(wù)邏輯處理,只要Controller return返回的Response交給worker處理即可,我們打開\vendor\topthink\think-worker\src\Application.php,看到worker方法中通過WorkerHttp對header重新處理,workerman對header只能通過WorkerHttp。

```php

use \Workerman\Connection\AsyncTcpConnection;

// 與遠(yuǎn)程連接池服務(wù)建立異步鏈接,ip為遠(yuǎn)程連接池服務(wù)的ip,如果是集群就是lvs的ip

$sql_connection = new AsyncTcpConnection('Text://ip:1234');

// 發(fā)送sql

$sql_connection->send("SELECT ... FROM .....");

// 異步獲得sql結(jié)果

$sql_connection->onMessage = function($sql_connection, $sql_result)

{

? ? // 這里只是打印結(jié)果

? ? var_dump(json_decode($task_result));

};

// 執(zhí)行異步鏈接

$sql_connection->connect();

```

```

public function worker($connection)

{

? ? try {

? ? ? ? ob_start();

? ? ? ? // 重置應(yīng)用的開始時(shí)間和內(nèi)存占用

? ? ? ? $this->beginTime = microtime(true);

? ? ? ? $this->beginMem? = memory_get_usage();

? ? ? ? // 銷毀當(dāng)前請求對象實(shí)例

? ? ? ? $this->delete('think\Request');

? ? ? ? $pathinfo = ltrim(strpos($_SERVER['REQUEST_URI'], '?') ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI'], '/');

? ? ? ? $this->request->setPathinfo($pathinfo);

? ? ? ? if ($this->config->get('session.auto_start')) {

? ? ? ? ? ? WorkerHttp::sessionStart();

}

? ? ? ? // 更新請求對象實(shí)例

? ? ? ? $this->route->setRequest($this->request);

? ? ? ? $response = $this->run();

? ? ? ? $response->send();

? ? ? ? $content = ob_get_clean();

? ? ? ? // Trace調(diào)試注入

? ? ? ? if ($this->env->get('app_trace', $this->config->get('app_trace'))) {

? ? ? ? ? ? $this->debug->inject($response, $content);

}

? ? ? ? $this->httpResponseCode($response->getCode());

? ? ? ? foreach ($response->getHeader() as $name => $val) {

? ? ? ? ? ? // 發(fā)送頭部信息

? ? ? ? ? ? WorkerHttp::header($name . (!is_null($val) ? ':' . $val : ''));

}

? ? ? ? $connection->send($content);

? ? } catch (HttpException $e) {

? ? ? ? $this->exception($connection, $e);

? ? } catch (\Exception $e) {

? ? ? ? $this->exception($connection, $e);

? ? } catch (\Throwable $e) {

? ? ? ? $this->exception($connection, $e);

}

}

```

我們按照原來thinkphp開發(fā)方式對異常進(jìn)行攔截

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容