PHP code example of chanshige / slim-bodycache

1. Go to this page and download the library: Download chanshige/slim-bodycache 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/ */

    

chanshige / slim-bodycache example snippets




$app = new \Slim\App();

// CacheConfig
$namespace = 'cache';
$defaultLifetime = 3600;
$directory = '/path/to/dir';

// Symfony Filesystem Cache
// PSR-6/16 Interfaceを持つコンポーネントを使用
$sfCache = new \Symfony\Component\Cache\Simple\FilesystemCache(
    $namespace,
    $defaultLifetime,
    $directory
);

// Register middleware
$app->add(new \Chanshige\Slim\BodyCache\Cache($sfCache));

// Fetch DI Container
$container = $app->getContainer();

$container['body_cache'] = function () use ($sfCache) {
    return new \Chanshige\Slim\BodyCache\Cache($sfCache);
};

// Json Response
$app->get('/foo', function (\Slim\Http\Request $request, \Slim\Http\Response $response) {
    
    if($request->getAttribute('has_body_cache')) {
        return $response
            ->withHeader("Content-type", "application/json;charset=utf-8");
    }

    return $response
        ->withStatus(200)
        ->withJson(['Hello World!!']);
})->add($container->get('body_cache'));

$app->run();