Skip to content

Instantly share code, notes, and snippets.

@BorisAnthony
Last active November 15, 2025 10:26
Show Gist options
  • Select an option

  • Save BorisAnthony/35608fca07a1d1bcb9f5534366f37fe5 to your computer and use it in GitHub Desktop.

Select an option

Save BorisAnthony/35608fca07a1d1bcb9f5534366f37fe5 to your computer and use it in GitHub Desktop.
Extend Laminas SapiEmitter to allow sending just body when headers or other output already sent
<?php
declare(strict_types=1);
namespace MyFramework\Emitter;
/**
* Extend Laminas SapiEmitter
* https://github.com/laminas/laminas-httphandlerrunner/blob/2.14.x/src/Emitter/SapiEmitter.php
* to add ability to emit body only, if headers or other output have already been sent.
* e.g.: by using var_dump(), print_r, or dump() for debugging.
*
* In case you're wondering,
* this does NOT work with HttpSoft's Emitter
* because its SapiEmitter::class is final:
* https://github.com/httpsoft/http-emitter/blob/master/src/SapiEmitter.php#L24
* // use HttpSoft\Emitter\SapiEmitter;
*
* USAGE:
*
* $emitter = new \MyFramework\Emitter\Emitter();
* $emitter->send($response);
*
*/
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use Psr\Http\Message\ResponseInterface;
class Emitter extends SapiEmitter
{
/**
* Send the response
* after checking if headers or any output has already been sent.
*
* This allows us to avoid "headers already sent" errors when using
* var_dump(), dump() or other output functions for debugging.
*/
public function send(ResponseInterface $response): void
{
if (headers_sent() or (ob_get_level() > 0 && ob_get_length() > 0)) {
$this->emitBody($response);
} else {
$this->emit($response);
}
}
/**
* Emit the message body.
* This overrides the parent method to make it public.
*/
public function emitBody(ResponseInterface $response): void
{
echo $response->getBody();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment