PHP code example of joby / smol-response

1. Go to this page and download the library: Download joby/smol-response library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

joby / smol-response example snippets


use Joby\Smol\Response\Response;

// Simple text response
$response = new Response(200, 'Hello World');

// JSON response
$response = Response::json(['status' => 'ok', 'data' => $results]);

// File download
$response = Response::file('/path/to/file.pdf');

// Redirect
$response = Response::redirect('https://example.com', permanent: true);

// Render the response
$renderer = new \Joby\Smol\Response\Renderer();
$renderer->render($response);

$response = (new Response(201, 'Created'))
    ->cachePublicContent()
    ->setStatus(200);

$status = new Status(404);
echo $status->code;           // 404
echo $status->reason_phrase;  // "Not Found"

$response->cache = CacheControl::publicMedia();
// Renders: public, max-age=31536000, s-maxage=31536000, 
//          stale-while-revalidate=31536000, stale-if-error=31536000

$response->cachePublicContent(); // Fluent helper method

$response->headers['content-type'] = 'application/json';
$response->headers['X-Custom-Header'] = 'value';

// Headers are automatically normalized to proper case
foreach ($response->headers as $name => $value) {
    echo "$name: $value\n";
    // Content-Type: application/json
    // X-Custom-Header: value
}

// With optional filename parameter (defaults to 'page.html')
$content = new StringContent('<h1>Hello World</h1>', 'custom.html');
$response->content = $content;

// Or set filename separately
$content = new StringContent('<h1>Hello World</h1>');
$content->setFilename('page.html');
$response->content = $content;

// Simple callback with optional filename parameter (defaults to 'page.html')
$content = new CallbackContent(function() {
    echo renderTemplate('page.html', ['title' => 'Welcome']);
}, 'welcome.html');

// With external data
$data = fetchDataFromDatabase();
$content = new CallbackContent(function() use ($data) {
    foreach ($data as $item) {
        echo "<li>{$item->name}</li>";
    }
});

// Supports any callable type
$content = new CallbackContent([$templateEngine, 'render'], 'output.html');
$response->content = $content;

$content = new JsonContent(['status' => 'ok', 'items' => $items]);
$response->content = $content;

// Filename defaults to basename of the file path
$content = new FileContent('/path/to/file.pdf');
$response->content = $content;

// Or override with custom filename
$content = new FileContent('/path/to/file.pdf', 'document.pdf');
$response->content = $content;

$response = new Response(204, new EmptyContent());

// Content automatically supports range requests
$content = new FileContent('/path/to/video.mp4');

// Apply a range manually
$ranged = new AppliedRangeContent($content, 0, 1024);
$response->content = $ranged;

// Renderer automatically sets 206 status and Content-Range header

class TemplateContent extends AbstractContent
{
    public function __construct(private string $template, private array $data) {
        $this->filename = 'page.html';
    }
    
    public function render(): void {
        echo $this->engine->render($this->template, $this->data);
    }
    
    public function size(): int|null {
        return null; // Unknown until rendered
    }
}

$renderer = new Renderer();
$renderer->render($response);

// Or test header generation without sending
$headers = $renderer->buildHeaders($response);

$response = Response::json($data)
    ->setStatus(201)
    ->cachePublicContent();

$response->headers['Location'] = '/api/resource/123';

echo $content->filename();       // 'document.pdf'
echo $content->mime();           // 'application/pdf'
echo $content->contentType();    // 'application/pdf'
echo $content->size();           // File size in bytes
echo $content->etag();           // MD5 hash for caching
echo $content->lastModified();   // DateTime of last modification

$path = '/var/www/public' . $_SERVER['REQUEST_URI'];

if (file_exists($path)) {
    $response = Response::file($path)->cachePublicMedia();
    (new Renderer())->render($response);
}

function apiSuccess($data, $code = 200) {
    return Response::json(['success' => true, 'data' => $data], $code)
        ->cacheNever();
}

function apiError($message, $code = 400) {
    return Response::json(['success' => false, 'error' => $message], $code)
        ->cacheNever();
}

$djot = file_get_contents('content.djot');
$html = renderDjotToHtml($djot);

$response = (new Response(200, $html))
    ->cachePublicContent();

$response->headers['Content-Type'] = 'text/html; charset=UTF-8';

// Template rendering with caching
$response = new Response(200, new CallbackContent(function() use ($templateEngine, $data) {
    echo $templateEngine->render('dashboard.html', $data);
}));
$response->cachePublicContent();

// Streaming output
$response = new Response(200, new CallbackContent(function() {
    foreach (generateLargeDataset() as $chunk) {
        echo json_encode($chunk) . "\n";
    }
}));