Browsing the archives for the optimization tag

Speeding up Requests with Reverse Routing Caching

Category CakePHP
This issue has been discussed by Tim and Matt in recent days and people got some performance changes.
From this I created an improved version of the AppHelper from Matt. My version is based on criteria cache.
For example, you can cache all back-end urls separated from the front-end urls using the criteria ‘prefix’.
Also, different from Matt version, it will use a separated cache config ‘_app_urls_’.
Below the code:
Update¹: I’ve updated the code to cache full urls properly. Thanks to Orcar for this catch.
<?php

class AppHelper extends Helper {
	public $_cache = array();
	public $_key = '';
	public $_criteria = array('prefix');
	public $_extras = array();
	public $_paramFields = array('controller', 'plugin', 'action', 'prefix');

	public function beforeRender() {
		if (is_a($this, 'HtmlHelper')) {
			$keys = array_intersect_key($this->params, array_combine($this->_criteria, $this->_criteria));
			$this->_key = 'url_map_' . implode('_', $keys);

			$this->_cache = Cache::read($this->_key, '_app_urls_');
			$this->_extras = array_intersect_key($this->params, array_combine($this->_paramFields, $this->_paramFields));
		}
	}

	public function afterLayout() {
		if (is_a($this, 'HtmlHelper')) {
			Cache::write($this->_key, $this->_cache, '_app_urls_');
		}
	}

	public function url($url = null, $full = false) {
		$keyUrl = $url;
		if (is_array($keyUrl)) {
			$keyUrl += $this->_extras;
			$keyUrl['full'] = $full;
		}

		$key = md5(serialize($keyUrl));
		if (!empty($this->_cache[$key])) {
			return $this->_cache[$key];
		}

		$url = parent::url($url, $full);
		$this->_cache[$key] = $url;

		return $url;
	}
}
Comments5 Comments