1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11: * @link http://cakephp.org CakePHP(tm) Project
12: * @since 3.0.0
13: * @license http://www.opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\Database\Schema;
16:
17: use Cake\Cache\Cache;
18: use Cake\Datasource\ConnectionInterface;
19:
20: /**
21: * Extends the schema collection class to provide caching
22: */
23: class CachedCollection extends Collection
24: {
25:
26: /**
27: * The name of the cache config key to use for caching table metadata,
28: * of false if disabled.
29: *
30: * @var string|bool
31: */
32: protected $_cache = false;
33:
34: /**
35: * Constructor.
36: *
37: * @param \Cake\Datasource\ConnectionInterface $connection The connection instance.
38: * @param string|bool $cacheKey The cache key or boolean false to disable caching.
39: */
40: public function __construct(ConnectionInterface $connection, $cacheKey = true)
41: {
42: parent::__construct($connection);
43: $this->cacheMetadata($cacheKey);
44: }
45:
46: /**
47: * {@inheritDoc}
48: *
49: */
50: public function describe($name, array $options = [])
51: {
52: $options += ['forceRefresh' => false];
53: $cacheConfig = $this->cacheMetadata();
54: $cacheKey = $this->cacheKey($name);
55:
56: if (!empty($cacheConfig) && !$options['forceRefresh']) {
57: $cached = Cache::read($cacheKey, $cacheConfig);
58: if ($cached !== false) {
59: return $cached;
60: }
61: }
62:
63: $table = parent::describe($name, $options);
64:
65: if (!empty($cacheConfig)) {
66: Cache::write($cacheKey, $table, $cacheConfig);
67: }
68:
69: return $table;
70: }
71:
72: /**
73: * Get the cache key for a given name.
74: *
75: * @param string $name The name to get a cache key for.
76: * @return string The cache key.
77: */
78: public function cacheKey($name)
79: {
80: return $this->_connection->configName() . '_' . $name;
81: }
82:
83: /**
84: * Sets the cache config name to use for caching table metadata, or
85: * disables it if false is passed.
86: * If called with no arguments it returns the current configuration name.
87: *
88: * @param bool|null $enable whether or not to enable caching
89: * @return string|bool
90: */
91: public function cacheMetadata($enable = null)
92: {
93: if ($enable === null) {
94: return $this->_cache;
95: }
96: if ($enable === true) {
97: $enable = '_cake_model_';
98: }
99:
100: return $this->_cache = $enable;
101: }
102: }
103: