Laravel 缓存标签的真实使用示例
Real world usage example of Laravel Cache Tags
根据LaravelDocumentation
Cache tags allow you to tag related items in the cache and then flush
all cached values that have been assigned a given tag. You may access
a tagged cache by passing in an ordered array of tag names. For
example, let's access a tagged cache and put value in the cache:
Cache::tags(['people', 'artists'])->put('John', $john, $minutes);
Cache::tags(['people', 'authors'])->put('Anne', $anne, $minutes);
它们有什么用?
正是文档中提到的内容。您可以使用标签对缓存进行分组,这样当您需要时,您可以按组清除它们。这真的取决于您的需求。
例如,如果您正在缓存产品:
Cache::put('product_' . $product->id, $product, $minutes);
假设您现在要从缓存中删除所有产品。您必须一个一个地清除具有模式 product_{id}
的每个缓存键,但是如果您使用公共键标记它们(例如 products
),您可以一次清除所有产品:
Cache::tags(['products'])->put('product_' . $product->id, $product, $minutes);
您还可以使用 artisan 命令清除特定标签:
php artisan cache:clear --tags=products
或以编程方式
Cache::tags('products')->flush();
根据LaravelDocumentation
Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. For example, let's access a tagged cache and put value in the cache:
Cache::tags(['people', 'artists'])->put('John', $john, $minutes);
Cache::tags(['people', 'authors'])->put('Anne', $anne, $minutes);
它们有什么用?
正是文档中提到的内容。您可以使用标签对缓存进行分组,这样当您需要时,您可以按组清除它们。这真的取决于您的需求。
例如,如果您正在缓存产品:
Cache::put('product_' . $product->id, $product, $minutes);
假设您现在要从缓存中删除所有产品。您必须一个一个地清除具有模式 product_{id}
的每个缓存键,但是如果您使用公共键标记它们(例如 products
),您可以一次清除所有产品:
Cache::tags(['products'])->put('product_' . $product->id, $product, $minutes);
您还可以使用 artisan 命令清除特定标签:
php artisan cache:clear --tags=products
或以编程方式
Cache::tags('products')->flush();