Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mcaskill/e2c500e9138dd65b9d0e639a4451305b to your computer and use it in GitHub Desktop.
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.
<?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