文件缓存

Symfony cache 在对象初始化的时候会调用 init 方法,用于区分处理不同适配器之间的差异。

在文件缓存初始化过程中,会初始化缓存存放的路径。可以通过配置文件中的 params 选项进行配置。如:

  1. <?php
  2. return [
  3. 'default' => [
  4. 'adapter' => \Symfony\Component\Cache\Adapter\FilesystemAdapter::class,
  5. 'params' => [
  6. 'directory' => '/tmp',
  7. ],
  8. ],
  9. ];

初始化代码:

  1. <?php
  2. namespace Symfony\Component\Cache\Adapter;
  3. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  4. trait FilesystemAdapterTrait
  5. {
  6. private $directory;
  7. private function init($namespace, $directory)
  8. {
  9. if (!isset($directory[0])) {
  10. $directory = sys_get_temp_dir().'/symfony-cache';
  11. } else {
  12. $directory = realpath($directory) ?: $directory;
  13. }
  14. if (isset($namespace[0])) {
  15. if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
  16. throw new InvalidArgumentException(sprintf('Namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
  17. }
  18. $directory .= DIRECTORY_SEPARATOR.$namespace;
  19. }
  20. if (!file_exists($directory)) {
  21. @mkdir($directory, 0777, true);
  22. }
  23. $directory .= DIRECTORY_SEPARATOR;
  24. // On Windows the whole path is limited to 258 chars
  25. if ('\\' === DIRECTORY_SEPARATOR && strlen($directory) > 234) {
  26. throw new InvalidArgumentException(sprintf('Cache directory too long (%s)', $directory));
  27. }
  28. $this->directory = $directory;
  29. }
  30. // ......
  31. }