vcn / symfony-writer
支持监听流的支持流写入库
v1.0.1
2019-12-04 07:23 UTC
Requires
- php: >=7.1
- ext-mbstring: *
- symfony/http-foundation: ^4.2 || ^5.0
This package is auto-updated.
Last update: 2024-09-04 17:38:28 UTC
README
vcn/symfony-writer 是一个库,它为 Symfony 的 StreamedResponse-class 提供了替代方案。与 StreamedResponse 不同,WriterResponse 允许您附加监听器并捕获正在响应的内容。
安装
在 symfony-project 中使用 composer 安装
composer require vcn/symfony-writer
使用方法
使用方法类似于 StreamedResponse 的使用方法,有一些小的变化
- 回调现在接受一个
\Vcn\Symfony\HttpFoundation\Writer
的实例作为第一个也是唯一的参数 - 而不是 echo,您应该使用
Writer::write
调用,并将要输出的数据作为字符串参数 - 在响应发送之前,您可以使用
Writer::attachListener
将监听器附加到响应上
示例
<?php namespace App; use Symfony\Component\HttpFoundation\Response; use Vcn\Symfony\HttpFoundation\Writer\Writer; use Vcn\Symfony\HttpFoundation\Writer\WriterResponse; class Controller { public function count(): Response { $response = new WriterResponse( function (Writer $writer) { for ($i = 0; $i < 50; $i++) { $writer->write("{$i} "); } } ); $tmpFile = tempnam(sys_get_temp_dir(), 'writer-response-'); $tmpFileHandle = fopen($tmpFile, 'w'); register_shutdown_function( function () use ($tmpFileHandle) { @fclose($tmpFileHandle); } ); error_log("Copy of response is sent to {$tmpFile}"); $response->attachListener( function (string $data) use ($tmpFileHandle) { fwrite($tmpFileHandle, $data); } ); return $response; } }