跳到内容

基于资源的缓存

编辑此页

当所有配置资源加载完毕后,您可能需要处理配置值并将它们合并到一个文件中。此文件充当缓存。其内容不必在每次应用程序运行时都重新生成 - 仅当配置资源被修改时才需要重新生成。

例如,Symfony Routing 组件允许您加载所有路由,然后基于这些路由转储 URL 匹配器或 URL 生成器。在这种情况下,当其中一个资源被修改时(并且您在开发环境中工作),生成的文件应该被无效化并重新生成。这可以通过使用 ConfigCache 类来实现。

下面的示例向您展示了如何收集资源,然后基于加载的资源生成一些代码,并将此代码写入缓存。缓存还接收用于生成代码的资源集合。通过查看这些资源的“最后修改”时间戳,缓存可以判断它是否仍然新鲜,或者是否应该重新生成其内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\Config\Resource\FileResource;

$cachePath = __DIR__.'/cache/appUserMatcher.php';

// the second argument indicates whether or not you want to use debug mode
$userMatcherCache = new ConfigCache($cachePath, true);

if (!$userMatcherCache->isFresh()) {
    // fill this with an array of 'users.yaml' file paths
    $yamlUserFiles = ...;

    $resources = [];

    foreach ($yamlUserFiles as $yamlUserFile) {
        // see the article "Loading resources" to
        // know where $delegatingLoader comes from
        $delegatingLoader->load($yamlUserFile);
        $resources[] = new FileResource($yamlUserFile);
    }

    // the code for the UserMatcher is generated elsewhere
    $code = ...;

    $userMatcherCache->write($code, $resources);
}

// you may want to require the cached code:
require $cachePath;

在调试模式下,一个 .meta 文件将在与缓存文件本身相同的目录中创建。这个 .meta 文件包含序列化的资源,其时间戳用于确定缓存是否仍然新鲜。当不在调试模式下时,缓存一旦存在就被认为是“新鲜”的,因此不会生成 .meta 文件。

您可以显式定义元文件的绝对路径

1
2
3
4
5
6
7
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\Config\Resource\FileResource;

$cachePath = __DIR__.'/cache/appUserMatcher.php';

// the third optional argument indicates the absolute path to the meta file
$userMatcherCache = new ConfigCache($cachePath, true, '/my/absolute/path/to/cache.meta');

7.1

自定义元文件路径的参数在 Symfony 7.1 中引入。

此作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本