多应用+插件架构,代码干净,支持一键云编译,码云点赞13K star,4.8-4.12 预售价格198元 广告
### **Cache** ### To extend the Laravel cache facility, we will use the extend method on the ``CacheManager``, which is used to bind a custom driver resolver to the manager, and is common across all manager classes. For example, to register a new cache driver named "mongo", we would do the following: ~~~ <!-- lang: php --> Cache::extend('mongo', function($app) { // Return Illuminate\Cache\Repository instance... }); ~~~ The first argument passed to the extend method is the name of the ``driver``. This will correspond to your driver option in the ``app/config/cache.php`` configuration file. The second argument is a Closure that should return an ``Illuminate\Cache\Repository`` instance. The Closure will be passed an ``$app`` instance, which is an instance of ``Illuminate\Foundation\Application`` and an IoC container. To create our custom cache driver, we first need to implement the ``Illuminate\Cache\StoreInterface`` contract. So, our MongoDB cache implementation would look something like this: ~~~ <!-- lang:php --> class MongoStore implements Illuminate\Cache\StoreInterface { public function get($key) {} public function put($key, $value, $minutes) {} public function increment($key, $value = 1) {} public function decrement($key, $value = 1) {} public function forever($key, $value) {} public function forget($key) {} public function flush() {} } ~~~ We just need to implement each of these methods using a MongoDB connection. Once our implementation is complete, we can finish our custom driver registeration: ~~~ <!-- lang:php --> use Illuminate\Cache\Repository; Cache::extend('mongo', function($app) { return new Repository(new MongoStore); } ~~~ As you can see in the example above, you may use the base ``Illuminate\Cache\Repository`` when creating custom cache drivers. These is typically no need to create your own repository class. If you're wondering where to put your custom cache driver code, consider making it available on Packagist! Or, you could create an ``Extensions`` namespace within your application's primary folder. For example, if the application is named ``Snappy``, you could place the cache extension in ``app/Snappy/Extensions/MongoStore.php``. However, keep in mind that Laravel doesn not have a rigid application structure and you are free to organize your application according to your preferences. > ### **Where To Extend?** ### > > If you're ever wondering where to put a piece of code, always consider a service provider. As we've discussed, using a service provider to organize framework extensions is a great way to organize your code.