Skip to content
This repository has been archived by the owner on Nov 12, 2020. It is now read-only.

Commit

Permalink
Merge pull request #12 from jkniest/develop
Browse files Browse the repository at this point in the history
Release 1.0.3
  • Loading branch information
jkniest committed Jan 7, 2018
2 parents b2190dd + 37b6405 commit 7658064
Show file tree
Hide file tree
Showing 12 changed files with 148 additions and 119 deletions.
1 change: 1 addition & 0 deletions .styleci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
preset: laravel
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ language: php

php:
- 7.1
- 7.2

cache:
directories:
Expand Down
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright 2017 Jordan Kniest
Copyright Jordan Kniest

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
Expand Down
6 changes: 6 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [1.0.3] - 2018-01-07
### Changed
- GET parameters are now considered in the cache generation
- Offical PHP 7.2 support

## [1.0.2] - 2017-11-21
### Changed
- Sites are not being cached if they do not have a 200 status code
Expand All @@ -21,3 +26,4 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

[1.0.1]: https://github.com/jkniest/HTMLCache/compare/1.0.0...1.0.1
[1.0.2]: https://github.com/jkniest/HTMLCache/compare/1.0.1...1.0.2
[1.0.3]: https://github.com/jkniest/HTMLCache/compare/1.0.2...1.0.3
36 changes: 15 additions & 21 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Laravel HTML Cache

[ ![Build](https://travis-ci.com/jkniest/HTMLCache.svg?token=V2HFFCLc6NVnxsqjqD9v&branch=develop) ](https://travis-ci.com/jkniest/HTMLCache) [![Latest Stable Version](https://poser.pugx.org/jkniest/htmlcache/v/stable)](https://packagist.org/packages/jkniest/htmlcache) [![Total Downloads](https://poser.pugx.org/jkniest/htmlcache/downloads)](https://packagist.org/packages/jkniest/htmlcache) [![License](https://poser.pugx.org/jkniest/htmlcache/license)](https://packagist.org/packages/jkniest/htmlcache)
[ ![Build](https://travis-ci.com/jkniest/HTMLCache.svg?token=V2HFFCLc6NVnxsqjqD9v&branch=develop) ](https://travis-ci.com/jkniest/HTMLCache) [![Latest Stable Version](https://poser.pugx.org/jkniest/htmlcache/v/stable)](https://packagist.org/packages/jkniest/htmlcache) [![Total Downloads](https://poser.pugx.org/jkniest/htmlcache/downloads)](https://packagist.org/packages/jkniest/htmlcache) [![License](https://poser.pugx.org/jkniest/htmlcache/license)](https://packagist.org/packages/jkniest/htmlcache) [ ![StyleCI](https://styleci.io/repos/100369160/shield?branch=develop&style=flat) ](https://styleci.io/repos/100369160)

---

Expand All @@ -10,7 +10,7 @@ This package is made for you if you have a lot of static pages (or pages that do

And it is highly customizable: You can even cache the same page for every user different, allowing that you can cache for example their account page or dashboard without worrying that another user can see these cached pages.

__One benefit against much other html caches:__ It will also cache the pages based on language, and (optionally) user id. And if there are special cases (for example a special GET-parameter) that needs to be used to generate multiple versions of the same page, the middleware can be easily modified.
__One benefit against much other html caches:__ It will also cache the pages based on language, and (optionally) user id. And if there are special cases (for example a specific session value) that needs to be used to generate multiple versions of the same page, the middleware can be easily modified.

---

Expand Down Expand Up @@ -42,6 +42,10 @@ The installation process is very straight-forward. It's like any other laravel p
composer require jkniest/htmlcache
```

__If you are using laravel 5.5 or higher the installation is already finished. You now have multiple ways to use the middleware (see [Using](#using)).__

Otherwise, if you use laravel 5.4 or lower go to step 2:

2) Add the package service provider in your packages configuration. Open up the `config/app.php` file and the following into your `providers` array:
```php
'providers' => [
Expand Down Expand Up @@ -127,7 +131,7 @@ In a few cases the pages will not be cached:

## Configuration

You can nearly configure anything inside the `.env` file.
You can configure nearly anything inside the `.env` file.

### Enable / Disable cache

Expand Down Expand Up @@ -187,21 +191,21 @@ This will create a new file in your project: `config/htmlcache.php`. There you c

## Clear cache

The html cache package uses the default laravel cache helpers. So you simple run the artisan command to clear the cache:
The html cache package uses the default laravel cache helpers. So you can run the artisan command to clear the cache:

```shell
php artisan cache:clear
```

This will remove every cached version of this plugin (and also of everything else). It is recommended to put this in your deployment workflow (for example in the deployment script in forge or as an deployment hook in envoyer)
This will remove every cached version of this plugin (and also everything else). It is recommended to put this in your deployment workflow (for example in the deployment script in forge or as a deployment hook in envoyer)

---

## Override middlware

It is possible to override the middleware. So you could override the cache-key generation. In this short tutorial we will add another field to the cache key generation (the post id).
It is possible to override the middleware. So you could override the cache-key generation. In this short tutorial we will add another field to the cache key generation (the current weekday).

Let's say you have a forum and you can access each page with a get parameter. For example: `http://my-forum.dev?page=3`. In the default implementation all pages would share the same cached results (which means that the pagination isn't working anymore).
Let's say you have a dashboard and all data on this dashboard will only update every weekday. In the default implementation you would have to set a maximum cache time (for example 1 day) but you can't be sure that the cache was generated exactly on 0am.

The simplest solution would be to override the middleware and extends the cache-key generation.

Expand All @@ -228,10 +232,11 @@ Now we can override any methods. The method `getCacheKey` handles the generation
$prefix = config('htmlcache.prefix');
$locale = app()->getLocale();

$page = str_replace('/', '_', trim($page, '/'));
$page = md5(trim($page, '/'));

if (config('htmlcache.user_specific')) {
$id = Auth::check() ? Auth::id() : -1;

return "{$prefix}{$page}_{$locale}_{$id}";
}

Expand All @@ -246,9 +251,7 @@ Let's implement our own (in the HtmlCache middleware that we just created):
{
$key = parent::getCacheKey($page);

if (request('page') !== null) {
$key .= '_' . request('page');
}
$key .= date('D');

return $key;
}
Expand All @@ -269,18 +272,9 @@ Of course you can always override any other method (like the `Handle` method its

---

## Roadmap

These are features that are planned for to upcoming versions. If you have any suggestion please let me know via issues or e-mail me at `contact@jkniest.de`

### Version 1.1.0
- Add native pagination support (so that the page GET parameter will also be cached)

---

## License

Copyright 2017 Jordan Kniest
Copyright Jordan Kniest

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
Expand Down
9 changes: 4 additions & 5 deletions src/HtmlCacheServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,26 @@
use Illuminate\Support\ServiceProvider;

/**
* The main service provider for this application
* The main service provider for this application.
*
* @category Core
* @package JKniest\HTMLCache
* @author Jordan Kniest <mail@jkniest.de>
* @license MIT <https://opensource.org/licenses/MIT>
* @link https://jkniest.de
*/
class HtmlCacheServiceProvider extends ServiceProvider
{
/**
* Bootstrapping the package
* Bootstrapping the package.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__ . '/config/htmlcache.php' => config_path('htmlcache.php')
__DIR__.'/config/htmlcache.php' => config_path('htmlcache.php'),
], 'htmlcache');

$this->mergeConfigFrom(__DIR__ . '/config/htmlcache.php', 'htmlcache');
$this->mergeConfigFrom(__DIR__.'/config/htmlcache.php', 'htmlcache');
}
}
37 changes: 18 additions & 19 deletions src/Http/Middleware/CacheHtml.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,22 @@
* visit the page. The effects are that no database queries needs to be executed.
*
* @category Core
* @package JKniest\HTMLCache
* @author Jordan Kniest <mail@jkniest.de>
* @license MIT <https://opensource.org/licenses/MIT>
* @link https://jkniest.de
*/
class CacheHtml
{
/**
* Handle the incoming request. If the caching is disabled or the request is not a GET
* Handle the incoming request. If the caching is disabled or if the request is not a GET
* request it will simply do nothing and only return the original response.
*
* If the caching is enabled and the user makes a GET request it tries to load the cached
* version of this page. If there is no cached version the original response will be returned
* and cached for the next time.
* and cached for the next time a user visits the page.
*
* @param Request $request The incoming request
* @param callable $next The next middleware
* @param Request $request The incoming request
* @param callable $next The next middleware
*
* @return Response
*/
Expand All @@ -49,10 +48,11 @@ public function handle(Request $request, $next)

/**
* Generate the cache key for a given page. It will have the following syntax:
* PREFIX_PAGE_LOCALE_USERID
* PREFIX_PAGE_LOCALE_USERID.
*
* The prefix is configurable in the config file. The page is the current page the user
* is visiting and the locale is the current locale (default: en).
* The prefix is configurable in the config file. The page is a hashed version of the current
* url (including GET parameters) that the user is visiting and the locale is the current
* locale (default: en).
*
* The user id is only set if the configuration value (htmlcache.user_specific) is set
* to true.
Expand All @@ -66,7 +66,7 @@ protected function getCacheKey(string $page)
$prefix = config('htmlcache.prefix');
$locale = app()->getLocale();

$page = str_replace('/', '_', trim($page, '/'));
$page = md5(trim($page, '/'));

if (config('htmlcache.user_specific')) {
$id = Auth::check() ? Auth::id() : -1;
Expand Down Expand Up @@ -108,36 +108,35 @@ protected function getIgnored()
*/
protected function isEnabled(Request $request)
{
return (
return
$request->method() === 'GET' &&
config('htmlcache.enabled') &&
!$request->is(... $this->getIgnored())
);
! $request->is(...$this->getIgnored());
}

/**
* Get the original or the cached response. If there is now cached version for the
* Get the original or the cached response. If there is no cached version for the
* current page it will run the full request cycle and cache the given response, if
* the returned status code is equals to 200.
*
* Otherwise, if there is a cache version, it will not run the whole request cycle
* and simply return the cached html / response.
* Otherwise if there is a cache version, it will not run the whole request cycle
* and simply return the cached html response.
*
* @param Request $request The incoming request
* @param callable $next The next middleware
* @param Request $request The incoming request
* @param callable $next The next middleware
*
* @return null|string
*/
protected function getContent(Request $request, callable $next)
{
$key = $this->getCacheKey($request->path());
$key = $this->getCacheKey($request->getRequestUri());
$time = config('htmlcache.minutes');

$content = Cache::remember($key, $time, function () use ($next, $request) {
$response = $next($request);

if ($response->getStatusCode() !== 200) {
return null;
return;
}

return $response->getContent();
Expand Down
14 changes: 7 additions & 7 deletions src/config/htmlcache.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

return [

/**
/*
* HTML cache enabled
*
* Should the html cache system be enabled? If this value is set to false it will
Expand All @@ -13,7 +13,7 @@
*/
'enabled' => env('HTML_CACHE_ENABLED', true),

/**
/*
* HTML cache prefix
*
* A cache prefix for the html cache. You should change this value if there are multiple
Expand All @@ -25,7 +25,7 @@
*/
'prefix' => env('HTML_CACHE_PREFIX', 'html_'),

/**
/*
* HTML cache time in minutes
*
* How many minutes should the response be cached? After this time (in minutes) the cache
Expand All @@ -36,7 +36,7 @@
*/
'minutes' => env('HTML_CACHE_MINUTES', 360),

/**
/*
* HTML cache user specific
*
* Should the cache be user specific? This would append the cache key by the user id. If the
Expand All @@ -52,13 +52,13 @@
*/
'user_specific' => env('HTML_CACHE_USER_SPECIFIC', false),

/**
/*
* HTML cache ignored routes
*
* These routes will be completely ignored by the caching. The only way to override these
* values is to publish the configuration file.
*/
'ignored' => [
# /path/to/my/ignored/route
]
// /path/to/my/ignored/route
],
];
20 changes: 11 additions & 9 deletions tests/BaseTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

namespace JKniest\Tests;

use Illuminate\Contracts\Debug\ExceptionHandler;
use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\Route;
use JKniest\HtmlCache\HtmlCacheServiceProvider;
use JKniest\HtmlCache\Http\Middleware\CacheHtml;
use Orchestra\Testbench\TestCase;

class BaseTestCase extends TestCase
{
Expand All @@ -15,18 +14,21 @@ protected function setUp()
parent::setUp();

Route::group(['middleware' => CacheHtml::class], function () {
Route::any('/example', function () {
return 'Example value: ' . request('test');
Route::get('/example', function () {
return 'Example value: '.session('test');
});
Route::any('/form', function () {
return 'Example value: '.request('test');
});
Route::get('/another', function () {
return 'Another value: ' . request('test');
return 'Another value: '.session('test');
});
Route::get('/error', function () {
return response('Error: ' . request('test'), 500);
return response('Error: '.session('test'), 500);
});
Route::get('/validation', function () {
request()->validate([
'name' => 'required'
'name' => 'required',
]);
});
});
Expand All @@ -35,7 +37,7 @@ protected function setUp()
protected function getPackageProviders($app)
{
return [
HtmlCacheServiceProvider::class
HtmlCacheServiceProvider::class,
];
}
}
}
14 changes: 0 additions & 14 deletions tests/ExampleTest.php

This file was deleted.

Loading

0 comments on commit 7658064

Please sign in to comment.