ホームページ >バックエンド開発 >PHPチュートリアル >Laravelでの簡略化されたストリーム応答処理

Laravelでの簡略化されたストリーム応答処理

Johnathan Smith
Johnathan Smithオリジナル
2025-03-05 16:25:12980ブラウズ

Simplified Stream Response Handling in Laravel

HTTPストリーム処理に対するLaravelの合理化されたアプローチにより、ファイルのダウンロードと転送が大幅に簡素化されます。 以前は、特に外部ソースからのファイルのダウンロードのために、ストリームの管理には、複数のステップとコンバージョンが含まれていました。 これで、resource()メソッドは簡潔なソリューションを提供します。

これは、アプリケーションのストレージにファイルを保存する場合に特に有益です。 resource()メソッドは、一時的なファイルと複雑なストリーム操作の必要性を排除します。

古い方法と新しい方法の比較:

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

// Older, more complex approach
$response = Http::get($url);
Storage::put('file.pdf', StreamWrapper::getResource(
    $response->toPsrResponse()->getBody()
));

// New, simplified approach using resource()
Storage::put('file.pdf', Http::get($url)->resource());
ドキュメント処理サービス内の実用的​​な例を調べましょう。

<?php namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use App\Exceptions\DocumentProcessingException;
use Exception;
use Illuminate\Support\Facades\Log;

class DocumentProcessor
{
    public function processRemoteDocument(string $documentUrl, string $reference)
    {
        try {
            $response = Http::timeout(30)->get($documentUrl);

            if (!$response->successful()) {
                throw new DocumentProcessingException(
                    "Document retrieval failed: {$response->status()}"
                );
            }

            // Store the original document
            $originalPath = "documents/{$reference}/original.pdf";
            Storage::put($originalPath, $response->resource());

            // Create a backup
            Storage::disk('backup')->writeStream(
                $originalPath,
                Storage::readStream($originalPath)
            );

            return [
                'reference' => $reference,
                'size' => Storage::size($originalPath),
                'path' => $originalPath
            ];
        } catch (Exception $e) {
            Log::error('Document processing error', [
                'url' => $documentUrl,
                'reference' => $reference,
                'error' => $e->getMessage()
            ]);

            throw $e;
        }
    }
}
メソッドは、Laravelでのストリームの処理を劇的に簡素化し、よりクリーンでより効率的なファイル操作をもたらします。

以上がLaravelでの簡略化されたストリーム応答処理の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。