4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation;
15 * StreamedResponse represents a streamed HTTP response.
17 * A StreamedResponse uses a callback for its content.
19 * The callback should use the standard PHP functions like echo
20 * to stream the response back to the client. The flush() method
21 * can also be used if needed.
25 * @author Fabien Potencier <fabien@symfony.com>
27 class StreamedResponse extends Response
34 * @param callable|null $callback A valid PHP callback or null to set it later
35 * @param int $status The response status code
36 * @param array $headers An array of response headers
38 public function __construct(callable $callback = null, $status = 200, $headers = array())
40 parent::__construct(null, $status, $headers);
42 if (null !== $callback) {
43 $this->setCallback($callback);
45 $this->streamed = false;
46 $this->headersSent = false;
50 * Factory method for chainability.
52 * @param callable|null $callback A valid PHP callback or null to set it later
53 * @param int $status The response status code
54 * @param array $headers An array of response headers
58 public static function create($callback = null, $status = 200, $headers = array())
60 return new static($callback, $status, $headers);
64 * Sets the PHP callback associated with this Response.
66 * @param callable $callback A valid PHP callback
70 public function setCallback(callable $callback)
72 $this->callback = $callback;
80 * This method only sends the headers once.
84 public function sendHeaders()
86 if ($this->headersSent) {
90 $this->headersSent = true;
92 return parent::sendHeaders();
98 * This method only sends the content once.
102 public function sendContent()
104 if ($this->streamed) {
108 $this->streamed = true;
110 if (null === $this->callback) {
111 throw new \LogicException('The Response callback must not be null.');
114 call_user_func($this->callback);
122 * @throws \LogicException when the content is not null
126 public function setContent($content)
128 if (null !== $content) {
129 throw new \LogicException('The content cannot be set on a StreamedResponse instance.');
140 public function getContent()