Created
July 3, 2019 14:30
-
-
Save mcaskill/e2c500e9138dd65b9d0e639a4451305b to your computer and use it in GitHub Desktop.
Charcoal : How to cache object data from a `CollectionLoader` into a `ModelLoader` cache namespace.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Pimple\Container; | |
use Charcoal\Model\ModelInterface; | |
use Charcoal\Model\CollectionInterface; | |
use App\Post; | |
$container = new Container(); | |
$container['cache'] = function (Container $container) { | |
// ... | |
}; | |
$container['model/collection/loader'] = function (Container $container) { | |
// ... | |
}; | |
/** | |
* Store an object in the main cache pool. | |
* | |
* @var Closure { | |
* @param ModelInterface $obj | |
* @borrows Container $container | |
* @return void | |
* } | |
*/ | |
$cacheObjModelFunc = function (ModelInterface $obj) use ($container) { | |
$objId = $obj->id(); | |
if ($objId) { | |
$cache = $container['cache']; | |
$objData = $obj->data(); | |
$objType = $obj->objType(); | |
$objKey = $obj->key(); | |
/** @see ModelLoader::cacheKey() */ | |
$cacheKey = 'objects/'.str_replace('/', '.', $objType.'.'.$objKey.'.'.$objId); | |
$cacheItem = $cache->getItem($cacheKey); | |
$cache->save($cacheItem->set($objData)); | |
} | |
}; | |
/** | |
* Collect all active Posts. | |
* | |
* @param Container $container The service locator. | |
* @borrows Closure $cacheObjModelFunc | |
* @return Post[]|CollectionInterface | |
*/ | |
$container['posts'] = function (Container $container) use ($cacheObjModelFunc) { | |
$loader = $container['model/collection/loader']; | |
$loader->setModel(Post::class) | |
->addOrder('publish_date', 'desc') | |
->addFilter('active', true) | |
->setCallback($cacheObjModelFunc); | |
return $loader->load(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment