Skip to content

Commit

Permalink
Merge pull request #43 from GeneaLabs/laravel-5.5
Browse files Browse the repository at this point in the history
Laravel 5.5
  • Loading branch information
mikebronner authored Dec 28, 2017
2 parents b0dccf8 + b09e1a6 commit a370197
Show file tree
Hide file tree
Showing 13 changed files with 175 additions and 59 deletions.
10 changes: 5 additions & 5 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ language: php
php:
- 7.0
- 7.1
- 7.2

before_script:
- travis_retry composer self-update
- travis_retry composer install --no-interaction --prefer-source --dev

script:
- ./vendor/bin/phpunit --coverage-text --coverage-clover ./build/logs/clover.xml
- mkdir -p ./build/logs
- ./vendor/bin/phpunit --coverage-text --coverage-clover ./build/logs/clover.xml

after_script:
- php vendor/bin/coveralls
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover ./build/logs/clover.xml
after_success:
- travis_retry php vendor/bin/php-coveralls -v

notifications:
webhooks:
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ 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).

## [0.2.13] - 28 Dec 2017
### Added
- ability to define custom cache store in `.env` file.

## [0.2.12] - 14 Dec 2017
### Added
- chainable method to disable caching of queries.
Expand Down
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,22 @@ relationships. This package is the attempt to address those requirements.
- PHP >= 7.0.0
- Laravel 5.5

## Installation
```
composer require genealabs/laravel-model-caching
```

## Configuration
### Optional Custom Cache Store
If you would like to use a different cache store than the default one used by
your Laravel application, you may do so by setting the `MODEL_CACHE_STORE`
environment variable in your `.env` file to the name of a cache store configured
in `config/cache.php` (you can define any custom cache store base on your
specific needs there). For example:
```
MODEL_CACHE_STORE=redis
```

## Usage
For best performance a taggable cache provider is recommended (redis,
memcached). While this is optional, using a non-taggable cache provider will
Expand Down Expand Up @@ -56,7 +72,7 @@ extends `Illuminate\Foundation\Auth\User`. Overriding that would break functiona
Not only that, but it probably isn't a good idea to cache the user model anyway,
since you always want to pull the most up-to-date info on it.

### Disabling Caching of Queries
### Optional Disabling Caching of Queries
**Recommendation: add this to all your seeder queries to avoid pulling in
cached information when reseeding multiple times.**
You can disable a given query by using `disableCache()` in the query chain, and
Expand Down
14 changes: 11 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,18 @@
}
],
"require": {
"php": ">=7.0.0",
"illuminate/cache": "5.5.*",
"illuminate/database": "5.5.*"
"illuminate/database": "5.5.*",
"php": ">=7.0.0"
},
"require-dev": {
"codedungeon/phpunit-result-printer": "^0.4.4",
"fzaninotto/faker": "~1.4",
"laravel/laravel": "5.5.*",
"mockery/mockery": "0.9.*",
"phpmd/phpmd": "^2.6",
"phpunit/phpunit": "5.7.*",
"satooshi/php-coveralls" : "*",
"php-coveralls/php-coveralls" : "*",
"sebastian/phpcpd": "*"
},
"autoload": {
Expand All @@ -34,5 +35,12 @@
"psr-4": {
"GeneaLabs\\LaravelModelCaching\\Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"providers": [
"GeneaLabs\\LaravelModelCaching\\Providers\\Service"
]
}
}
}
5 changes: 5 additions & 0 deletions config/laravel-model-caching.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

return [
'store' => env('MODEL_CACHE_STORE'),
];
6 changes: 4 additions & 2 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
printerClass="Codedungeon\PHPUnitPrettyResultPrinter\Printer"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="vendor/autoload.php"
>
<testsuites>
<testsuite name="Feature">
Expand Down
21 changes: 0 additions & 21 deletions src/CachedBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ class CachedBuilder extends EloquentBuilder
{
use Cachable;

protected $isCachable = true;

public function avg($column)
{
if (! $this->isCachable) {
Expand Down Expand Up @@ -56,13 +54,6 @@ public function delete()
return parent::delete();
}

public function disableCache()
{
$this->isCachable = false;

return $this;
}

/**
* @SuppressWarnings(PHPMD.ShortVariable)
*/
Expand Down Expand Up @@ -155,16 +146,4 @@ public function sum($column)
return parent::sum($column);
});
}

protected function makeCacheKey(array $columns = ['*'], $idColumn = null) : string
{
return (new CacheKey($this->eagerLoad, $this->model, $this->query))
->make($columns, $idColumn);
}

protected function makeCacheTags() : array
{
return (new CacheTags($this->eagerLoad, $this->model))
->make();
}
}
27 changes: 3 additions & 24 deletions src/CachedModel.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php namespace GeneaLabs\LaravelModelCaching;

use GeneaLabs\LaravelModelCaching\CachedBuilder as Builder;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Cache\CacheManager;
use Illuminate\Cache\TaggableStore;
use Illuminate\Cache\TaggedCache;
Expand All @@ -12,6 +13,8 @@

abstract class CachedModel extends Model
{
use Cachable;

public function newEloquentBuilder($query)
{
if (session('genealabs-laravel-model-caching-is-disabled')) {
Expand Down Expand Up @@ -46,30 +49,6 @@ public static function boot()
});
}

public function cache(array $tags = [])
{
$cache = cache();

if (is_subclass_of($cache->getStore(), TaggableStore::class)) {
array_push($tags, str_slug(get_called_class()));
$cache = $cache->tags($tags);
}

return $cache;
}

public function disableCache() : self
{
session(['genealabs-laravel-model-caching-is-disabled' => true]);

return $this;
}

public function flushCache(array $tags = [])
{
$this->cache($tags)->flush();
}

public static function all($columns = ['*'])
{
$class = get_called_class();
Expand Down
14 changes: 14 additions & 0 deletions src/Providers/Service.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php namespace GeneaLabs\LaravelModelCaching\Providers;

use Illuminate\Support\ServiceProvider;

class Service extends ServiceProvider
{
protected $defer = false;

public function boot()
{
$configPath = __DIR__ . '/../../config/laravel-model-caching.php';
$this->mergeConfigFrom($configPath, 'laravel-model-caching');
}
}
38 changes: 38 additions & 0 deletions src/Traits/Cachable.php
Original file line number Diff line number Diff line change
@@ -1,17 +1,55 @@
<?php namespace GeneaLabs\LaravelModelCaching\Traits;

use GeneaLabs\LaravelModelCaching\CacheKey;
use GeneaLabs\LaravelModelCaching\CacheTags;
use GeneaLabs\LaravelModelCaching\CachedModel;
use Illuminate\Cache\TaggableStore;

trait Cachable
{
protected $isCachable = true;

protected function cache(array $tags = [])
{
$cache = cache();

if (config('laravel-model-caching.store')) {
$cache = $cache->store(config('laravel-model-caching.store'));
}

if (is_subclass_of($cache->getStore(), TaggableStore::class)) {
if (is_a($this, CachedModel::class)) {
array_push($tags, str_slug(get_called_class()));
}

$cache = $cache->tags($tags);
}

return $cache;
}

public function disableCache()
{
session(['genealabs-laravel-model-caching-is-disabled' => true]);
$this->isCachable = false;

return $this;
}

public function flushCache(array $tags = [])
{
$this->cache($tags)->flush();
}

protected function makeCacheKey(array $columns = ['*'], $idColumn = null) : string
{
return (new CacheKey($this->eagerLoad, $this->model, $this->query))
->make($columns, $idColumn);
}

protected function makeCacheTags() : array
{
return (new CacheTags($this->eagerLoad, $this->model))
->make();
}
}
2 changes: 2 additions & 0 deletions tests/CreatesApplication.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php namespace GeneaLabs\LaravelModelCaching\Tests;

use GeneaLabs\LaravelModelCaching\Providers\Service as LaravelModelCachingService;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Eloquent\Factory;

Expand All @@ -13,6 +14,7 @@ public function createApplication()
$app->afterResolving('migrator', function ($migrator) {
$migrator->path(__DIR__ . '/database/migrations');
});
$app->register(LaravelModelCachingService::class);

return $app;
}
Expand Down
3 changes: 0 additions & 3 deletions tests/Unit/CachedModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,6 @@ public function testAllModelResultsCreatesCache()
$this->assertEmpty($liveResults->diffAssoc($cachedResults));
}

/**
* @group test
**/
public function testScopeDisablesCaching()
{
$key = 'genealabslaravelmodelcachingtestsfixturesauthor';
Expand Down
72 changes: 72 additions & 0 deletions tests/Unit/Traits/CachableTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php namespace GeneaLabs\LaravelModelCaching\Tests\Unit;

use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Author;
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Book;
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Profile;
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Publisher;
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Store;
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\UncachedAuthor;
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\UncachedBook;
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\UncachedProfile;
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\UncachedPublisher;
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\UncachedStore;
use GeneaLabs\LaravelModelCaching\Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class CachableTest extends TestCase
{
use RefreshDatabase;

public function setUp()
{
parent::setUp();

cache()->flush();
$publishers = factory(Publisher::class, 10)->create();
factory(Author::class, 10)->create()
->each(function ($author) use ($publishers) {
factory(Book::class, random_int(2, 10))->make()
->each(function ($book) use ($author, $publishers) {
$book->author()->associate($author);
$book->publisher()->associate($publishers[rand(0, 9)]);
$book->save();
});
factory(Profile::class)->make([
'author_id' => $author->id,
]);
});

$bookIds = (new Book)->all()->pluck('id');
factory(Store::class, 10)->create()
->each(function ($store) use ($bookIds) {
$store->books()->sync(rand($bookIds->min(), $bookIds->max()));
});
cache()->flush();
}

public function testSpecifyingAlternateCacheDriver()
{
$configCacheStores = config('cache.stores');
$configCacheStores['customCache'] = ['driver' => 'array'];
config(['cache.stores' => $configCacheStores]);
config(['laravel-model-caching.store' => 'customCache']);
$key = 'genealabslaravelmodelcachingtestsfixturesauthor';
$tags = ['genealabslaravelmodelcachingtestsfixturesauthor'];

$authors = (new Author)
->all();
$defaultcacheResults = cache()
->tags($tags)
->get($key);
$customCacheResults = cache()
->store('customCache')
->tags($tags)
->get($key);
$liveResults = (new UncachedAuthor)
->all();

$this->assertEquals($customCacheResults, $authors);
$this->assertNull($defaultcacheResults);
$this->assertEmpty($liveResults->diffAssoc($customCacheResults));
}
}

0 comments on commit a370197

Please sign in to comment.