Slim Framework HTTP cache middleware and service provider

Overview

Slim Framework HTTP Cache

Build Status Coverage Status Latest Stable Version License

This repository contains a Slim Framework HTTP cache middleware and service provider.

Install

Via Composer

$ composer require slim/http-cache

Requires Slim 4.0.0 or newer.

Usage

declare(strict_types=1);

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

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

$app = \Slim\Factory\AppFactory::create();

// Register the http cache middleware.
$app->add(new \Slim\HttpCache\Cache('public', 86400));

// Create the cache provider.
$cacheProvider = new \Slim\HttpCache\CacheProvider();

// Register a route and let the closure callback inherit the cache provider.
$app->get(
    '/',
    function (Request $request, Response $response, array $args) use ($cacheProvider): Response {
        // Use the cache provider.
        $response = $cacheProvider->withEtag($response, 'abc');

        $response->getBody()->write('Hello world!');

        return $response;
    }
);

$app->run();

Testing

$ phpunit

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Update the cache middleware to support slim 4

    Update the cache middleware to support slim 4

    Heya 👋

    So I'm not sure if this PR is going in the right direction but I noticed that we couldn't use this as middleware in the latest slim framework (v4). I've updated the implementation to match the MiddlewareInterface and updated the tests so they create the required classes in the right way.

    One thing I'm not sure on is whether the use of slim/psr-7 is desired, I think i only really use it to easily create request/response objects. In the main slim repo I've noticed we do it slightly differently but I don't know if how I've written the tests is an issue here. What do you think?

    Lastly while I've got the suite green I just want to sanity check this middleware on v4 of the framework but wanted to get some early feedback on whether this is something that you guys wanted.

    Thanks

    TODO

    • [ ] Test this middleware against v4 of slim/slim
    opened by studioromeo 5
  • Welcome middleware

    Welcome middleware

    Hey,

    Nice to see your cache middleware. I was looking at the code, and find it also suits Conduit and may be others which are PSR-7 framework.

    Some questions / concerns :

    1 . I think the CacheProvider is mainly for Pimple . May be we can move that also to require-dev ?

    As I am not so closely watching Slim, ( even I am watching) I may have missed whether you said of splitting the PSR-Http of Slim. Any plans of splitting to standalone component ?

    Thank you

    opened by harikt 4
  • Slim 4 compatibility

    Slim 4 compatibility

    I made an attempt to make this Slim 4 compatible. Please check https://github.com/adriansuter/Slim-HttpCache/tree/patch-slim4

    @l0gicgate I could make a PR against a new branch if you like.

    README is not updated yet.

    opened by adriansuter 2
  • http cache method on controller methods

    http cache method on controller methods

    Hi, Am trying to get the slim cache provider to work on controller methods but am not able to reach a solution. I have added the HTTP cache provider from composer following the steps from this Slim Page and even added it through dependency injection. Then I have a method that needs to return a JSON response with cache expires to my client app. I have done the tests in Postman and am getting the "Slim application error" Here is my settup>> $app=new Slim\App(); $app->add(new \Slim\HttpCache\Cache('public', 86400)); //require dependencies require './app/dependencies.php'; //require routes require './app/routes.php'; $app->run();

    here is the dependencies file>> <?php $container=$app->getContainer(); $container['cache'] = function () { return new \Slim\HttpCache\CacheProvider(); }; $container['UserController']= function (){ return new UserController(); }; $container['SongsController']= function (){ return new SongsController(); };

    Here is part of the routes file>> $app->get('/login', 'UserController:login'); $app->get('/songs/all[/{offset}]', 'SongsController:all');

    And finally the method in SongsController that should return the result with cache is this>>

    ` public function all($request, $response, $args){ $res=array(); $uid= $this->authToken();

        if ($uid){
            //proceed
            $body=$request->getQueryParams();
            $offset=isset($body['offset']) ? $body['offset'] : 0;
            $res['success']=1;
            $res['messages']="Songs retrieved";
            $res['uid']=$uid;
            $res['audios']=  $this->getAllAudios($offset);
        }else{
            $res['success']=3;
            $res['message']="Access denied! Please login to proceed";
        }         
            $response->withJson($res);
    
            $newResponse = $this->cache->withExpires($response, time() + 3600);
        return $newResponse;
    }`
    
    opened by jaymoh 2
  • does not work

    does not work

    Response header:

    Cache-Control:no-store, no-cache, must-revalidate Cache-Control:public, max-age=86400 ETag:"default_css"

    then the client asks it again, whitout the etag.

    opened by sirber 2
  • Problem with slim 4

    Problem with slim 4

    I tried it to add it to slim 4 but I get the error

    Fatal error: Uncaught TypeError: Argument 2 passed to Slim\HttpCache\Cache::__invoke() must be an instance of Psr\Http\Message\ResponseInterface, instance of Slim\Routing\RouteRunner given, called in /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php on line 283 and defined in /var/www/html/vendor/slim/http-cache/src/Cache.php:53 Stack trace: #0 /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php(283): Slim\HttpCache\Cache->__invoke(Object(Slim\Http\ServerRequest), Object(Slim\Routing\RouteRunner)) #1 /var/www/html/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php(98): class@anonymous->handle(Object(Slim\Http\ServerRequest)) #2 /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php(140): Slim\Middleware\ErrorMiddleware->process(Object(Slim\Http\ServerRequest), Object(class@anonymous)) #3 /var/www/html/vendor/slim/slim/Slim/MiddlewareDispatcher.php(81): class@anonymous->handle(Object(Slim\Http\ServerRequest)) #4 /var/www/html/vendor/slim/slim/Slim/App.php(211): Slim\MiddlewareDispatcher->handle( in /var/www/html/vendor/slim/http-cache/src/Cache.php on line 53

    Took a peak into the middleware and the __invoke method didn't have the correct arguments. So is it just not ready form slim 4 or did I missed something?

    opened by X-Tender 1
  • Need to specify a target version for phpunit?

    Need to specify a target version for phpunit?

    When Travis tests on php version 7 it installs a newer version of phpunit.

    This results in the error PHP Fatal error: Class 'PHPUnit_Framework_TestCase' not found in /home/travis/build/slimphp/Slim-HttpCache/tests/CacheProviderTest.php on line 7 (example)

    This happens because phpunit version 6 released on 2017-02-03 is namespaced. You will need to refactor things like \PHPUnit_Framework_TestCase to \PHPUnit\Framework\TestCase

    opened by andybeak 1
  • rename service

    rename service

    i would suggest renaming service to httpCache as under cache key there is often some kind of cache backends manager providing caching abilities to the application

    opened by kminek 1
  • Unbind the Service Provider from the main code

    Unbind the Service Provider from the main code

    From https://github.com/slimphp/Slim/issues/1275#issuecomment-110006099:

    Can we stop coupling the ServiceProvider with the actual code for the package. I see this is becoming a pattern that others will follow. Now that we are using Container Interop, we shouldn't bind the actual package to the Pimple ServiceProviderInterface, we should create a separate class in each package to do this.

    opened by akrabat 1
  • Update phpstan/phpstan requirement from ^0.12.28 to ^0.12.28 || ^1.0.0

    Update phpstan/phpstan requirement from ^0.12.28 to ^0.12.28 || ^1.0.0

    Updates the requirements on phpstan/phpstan to permit the latest version.

    Release notes

    Sourced from phpstan/phpstan's releases.

    1.2.0

    Improvements 🔧

    Bugfixes 🐛

    Function signature fixes 🤖

    Commits
    • cbe085f PHPStan 1.2.0
    • 8170c41 Levels start at 0, so there are 10 levels
    • 4d6fefa Updated PHPStan to commit c862bb97482bced730988217685a8ae019436ad6
    • e33400f Updated PHPStan to commit 5a0d0314ea20b905e952670820554c541db8029c
    • 39d0d4e Update text to note that level 9 is the strictest
    • 898dca3 Updated PHPStan to commit b42ceb618accbe20651165b0a049da299013e273
    • b79d8d0 Updated PHPStan to commit 480c516ce2795d7af27142ac7c370e0d1f6bbb38
    • 362e194 Updated PHPStan to commit 7ed316d5983eb5a2601a5c3eb7781f8c06a50503
    • bc99be7 Updated PHPStan to commit db456dd6fd79405bbbdac00fddb8ca0acb90ed49
    • a0a82d2 Open 1.2-dev
    • Additional commits viewable in compare view

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 0
  • Upgrade to GitHub-native Dependabot

    Upgrade to GitHub-native Dependabot

    Dependabot Preview will be shut down on August 3rd, 2021. In order to keep getting Dependabot updates, please merge this PR and migrate to GitHub-native Dependabot before then.

    Dependabot has been fully integrated into GitHub, so you no longer have to install and manage a separate app. This pull request migrates your configuration from Dependabot.com to a config file, using the new syntax. When merged, we'll swap out dependabot-preview (me) for a new dependabot app, and you'll be all set!

    With this change, you'll now use the Dependabot page in GitHub, rather than the Dependabot dashboard, to monitor your version updates, and you'll configure Dependabot through the new config file rather than a UI.

    If you've got any questions or feedback for us, please let us know by creating an issue in the dependabot/dependabot-core repository.

    Learn more about migrating to GitHub-native Dependabot

    Please note that regular @dependabot commands do not work on this pull request.

    dependencies 
    opened by dependabot-preview[bot] 0
  • {} is not resolvable

    {} is not resolvable

    I am trying to add caching to Slim 3, I followed the instruction in https://www.slimframework.com/docs/v3/features/caching.html :

    $app = new Slim\App(['settings' => $config]);
    $container = $app->getContainer();
    $container['cache'] = function () {
        return new \Slim\HttpCache\CacheProvider();
    };
    $app->add(new \Slim\HttpCache\Cache('public', 86400));
    

    but I get the following error :

    {
    "message": "Slim Application Error",
    "exception": [
    {
    "type": "RuntimeException",
    "code": 0,
    "message": "{} is not resolvable",
    "file": "C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\CallableResolver.php",
    "line": 113,
    "trace": [
    "#0 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\CallableResolver.php(61): Slim\CallableResolver->assertCallable(Object(Slim\HttpCache\Cache))",
    "#1 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\CallableResolverAwareTrait.php(41): Slim\CallableResolver->resolve(Object(Slim\HttpCache\Cache))",
    "#2 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\DeferredCallable.php(50): Slim\DeferredCallable->resolveCallable(Object(Slim\HttpCache\Cache))",
    "#3 [internal function]: Slim\DeferredCallable->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response), Object(Slim\App))",
    "#4 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(70): call_user_func(Object(Slim\DeferredCallable), Object(Slim\Http\Request), Object(Slim\Http\Response), Object(Slim\App))",
    "#5 C:\Users\Mima\Desktop\file\app\server\src\classes\middlewares\TrailingSlash.php(29): Slim\App->Slim\{closure}(Object(Slim\Http\Request), Object(Slim\Http\Response))",
    "#6 [internal function]: App\Middleware\TrailingSlash->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response), Object(Closure))",
    "#7 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\DeferredCallable.php(57): call_user_func_array(Object(App\Middleware\TrailingSlash), Array)",
    "#8 [internal function]: Slim\DeferredCallable->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response), Object(Closure))",
    "#9 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(70): call_user_func(Object(Slim\DeferredCallable), Object(Slim\Http\Request), Object(Slim\Http\Response), Object(Closure))",
    "#10 C:\Users\Mima\Desktop\file\app\server\src\public\index.php(1047): Slim\App->Slim\{closure}(Object(Slim\Http\Request), Object(Slim\Http\Response))",
    "#11 [internal function]: Closure->{closure}(Object(Slim\Http\Request), Object(Slim\Http\Response), Object(Closure))",
    "#12 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\DeferredCallable.php(57): call_user_func_array(Object(Closure), Array)",
    "#13 [internal function]: Slim\DeferredCallable->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response), Object(Closure))",
    "#14 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(70): call_user_func(Object(Slim\DeferredCallable), Object(Slim\Http\Request), Object(Slim\Http\Response), Object(Closure))",
    "#15 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(117): Slim\App->Slim\{closure}(Object(Slim\Http\Request), Object(Slim\Http\Response))",
    "#16 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\App.php(392): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))",
    "#17 C:\Users\Mima\Desktop\file\app\server\src\vendor\slim\slim\Slim\App.php(297): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))",
    "#18 C:\Users\Mima\Desktop\file\app\server\src\public\index.php(1059): Slim\App->run()",
    "#19 {main}"
    ]
    }
    ]
    }
    
    opened by NassimaZIANI 0
  • Fixed relative max-age format

    Fixed relative max-age format

    $cacheProvider->allowCache($response, 'private', '+12 hours');
    // should not be: private, max-age=1539965032
    // but should be: private, max-age=43200
    
    opened by izayoi256 0
  • Slim requirement

    Slim requirement

    Readme says that this project require slim 3 or newer... It seems that this can be use with any psr7 library that can handle middleware in the same way then slim3. Am I wrong ?

    opened by lalop 0
  • Abort execution early if client side cache is still valid

    Abort execution early if client side cache is still valid

    I wonder if the current implementation of the HTTP Cache is really performant. To me, it looks like the cache middleware creates the whole response first and then compares the Last-Modified and ETag header of the response with the request to determine if a 304 status code should be returned. Therefore the complete response is created but will not be used, since Slim will not output the body if the status is 304.

    In Slim 2 the abort method was used to immediately stop the execution as soon as the Last-Modified/ETag were set (assuming the client side cache was still valid). I think it would also be a good idea for Slim 3 to return the 304 response as soon as possible. This will make the usage a bit more verbose and not automagically, but will probably improve CPU/memory usage and response times.

    For example, the current checks in the Cache middleware could be moved to a new method in the cache provider (e.g. isStillValid()):

    $app->get('/foo', function ($req, $res, $args) {
        $resWithEtag = $this['cache']->withEtag($res, 'abc');
    
        if ($this['cache']->isStillValid($req, $res)) {
            return $resWithEtag->withStatus(304); // or even another convenience method
        }
    
        //  ... some intensive calls to create the response
        $resWithEtag->write($body);
    
        return $resWithEtag;
    });
    
    opened by micheh 2
Releases(1.1.0)
Owner
Slim Framework
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
Slim Framework
Slim Framework flash messages service provider

Slim Framework Flash Messages This repository contains a Slim Framework Flash messages service provider. This enables you to define transient messages

Slim Framework 143 Dec 11, 2022
A Slim Framework Flash messages service provider

Slim Framework Flash Messages This repository contains a Slim Framework Flash messages service provider. This enables you to define transient messages

Slim Framework 143 Dec 11, 2022
Symprowire is a PHP MVC Framework based and built on Symfony, using the ProcessWire CMS as DBAL and Service Provider.

Symprowire - PHP MVC Framework for ProcessWire 3.x Symprowire is a PHP MVC Framework based and built on Symfony using ProcessWire 3.x as DBAL and Serv

Luis Mendez 7 Jan 16, 2022
This repository contains a library of optional middleware for your Slim Framework application

Slim Framework Middleware This repository contains a library of optional middleware for your Slim Framework application. How to Install Update your co

Slim Framework 47 Nov 7, 2022
Juliangut Slim Framework Doctrine handler middleware

Juliangut Slim Framework Doctrine handler middleware Doctrine handler middleware for Slim Framework. Slim3 version Doctrine integration service for Sl

Julián Gutiérrez 6 Mar 23, 2021
This Slim Framework middleware will compile LESS CSS files on-the-fly using the Assetic library

This Slim Framework middleware will compile LESS CSS files on-the-fly using the Assetic library. It supports minification and caching, also via Asseti

Gerard Sychay 22 Mar 31, 2020
Access control middleware for Slim framework

Slim Access Access control middleware for Slim framework. Supported formats IPv4 and IPv6 addresses CIDR notation all keyword Installation composer re

Alexandre Bouvier 7 Oct 22, 2019
CORS Middleware for PHP Slim Framework

CorsSlim Cross-origin resource sharing (CORS) Middleware for PHP Slim Framework. Usage Composer Autoloader Install with Composer Update your composer.

Palani Kumanan 92 Nov 30, 2021
PHP slim framework middleware to minify HTML output

slim-minify Slim middleware to minify HTML output generated by the slim PHP framework. It removes whitespaces, empty lines, tabs beetween html-tags an

Christian Klisch 35 Oct 31, 2021
Slim Framework CSRF protection middleware

Slim Framework CSRF Protection This repository contains a Slim Framework CSRF protection PSR-15 middleware. CSRF protection applies to all unsafe HTTP

Slim Framework 302 Dec 11, 2022
High performance HTTP Service Framework for PHP based on Workerman.

webman High performance HTTP Service Framework for PHP based on Workerman. Manual https://www.workerman.net/doc/webman Benchmarks https://www.techempo

walkor 1.3k Jan 2, 2023
💫 Vega is a CLI mode HTTP web framework written in PHP support Swoole, WorkerMan / Vega 是一个用 PHP 编写的 CLI 模式 HTTP 网络框架,支持 Swoole、WorkerMan

Mix Vega 中文 | English Vega is a CLI mode HTTP web framework written in PHP support Swoole, WorkerMan Vega 是一个用 PHP 编写的 CLI 模式 HTTP 网络框架,支持 Swoole、Work

Mix PHP 46 Apr 28, 2022
Async HTTP proxy connector, tunnel any TCP/IP-based protocol through an HTTP CONNECT proxy server, built on top of ReactPHP.

clue/reactphp-http-proxy Async HTTP proxy connector, tunnel any TCP/IP-based protocol through an HTTP CONNECT proxy server, built on top of ReactPHP.

Christian Lück 43 Dec 25, 2022
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

Slim Framework Slim is a PHP micro-framework that helps you quickly write simple yet powerful web applications and APIs. Installation It's recommended

Slim Framework 11.5k Jan 4, 2023
A curated list of awesome tutorials and other resources for the Slim micro framework

Awesome Slim A curated list of awesome tutorials and other resources for the Slim micro framework Table of Contents Essentials Tutorials Packages and

Sawyer Charles 466 Dec 8, 2022
PHP boilerplate for quick start projects using Slim Framework and Eloquent.

Lassi PHP boilerplate for quick projects using Slim Framework and Eloquent database. Lassi is a small PHP boilerplate to use Slim Framework with Eloqu

Jabran Rafique⚡️ 59 Jul 14, 2022
Slim Framework - Prerequisite Checker

Slim Framework - Server Configuration Checker Upload the file check.php to your webserver Browse to the file: https://example.com/check.php Check the

Daniel Opitz 6 Aug 30, 2022
REST APIs using Slim framework. Implemented all CRUD operations on the MySql database

PHP REST API using slim framework and CRUD operations ?? Hi there, this is a simple REST API built using the Slim framework. And this is for the folks

Hanoak 2 Jun 1, 2022
A Slim PHP MVC framework built just for fun!

Aura Framework A Slim PHP MVC framework built just for fun! en: Note: This repository only contains the core code of the Aura framework. If you want t

Murilo Magalhães Barreto 2 Dec 16, 2021