Context in PHP

Here’s the translated PHP code with explanation in Markdown format suitable for Hugo:

Our first program demonstrates handling HTTP requests with context in PHP. Here’s the full source code:

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/vendor/autoload.php';

$app = AppFactory::create();

$app->get('/hello', function (Request $request, Response $response) {
    $context = $request->getAttribute('request_context');
    echo "server: hello handler started\n";

    $start = time();
    while (time() - $start < 10) {
        if ($context['cancelled']) {
            echo "server: " . $context['error'] . "\n";
            return $response->withStatus(500)->withHeader('Content-Type', 'text/plain')->write($context['error']);
        }
        usleep(100000); // Sleep for 100ms
    }

    echo "server: hello handler ended\n";
    return $response->withHeader('Content-Type', 'text/plain')->write("hello\n");
});

// Middleware to simulate context
$app->add(function ($request, $handler) {
    $context = ['cancelled' => false, 'error' => ''];
    $request = $request->withAttribute('request_context', $context);

    // Simulate cancellation after 2 seconds
    register_shutdown_function(function () use (&$context) {
        sleep(2);
        $context['cancelled'] = true;
        $context['error'] = 'context canceled';
    });

    return $handler->handle($request);
});

$app->run();

In this example, we’re using the Slim framework to create a simple HTTP server. The /hello route simulates a long-running operation that can be cancelled.

A request context is simulated using middleware. In a real-world scenario, you might use a more sophisticated method to handle request cancellation.

The handler checks the context periodically to see if the request has been cancelled. If it has, it returns an error response. Otherwise, it completes after 10 seconds and returns a success response.

To run the server:

$ php -S localhost:8090 index.php &

Simulate a client request to /hello, and interrupt it shortly after:

$ curl localhost:8090/hello
server: hello handler started
^C
server: context canceled

This example demonstrates how to handle long-running operations in a web server context, allowing for cancellation of requests. While PHP doesn’t have built-in support for contexts like some other languages, we can achieve similar functionality using request attributes and careful handling of long-running processes.