Caching with AOP in FLOW3
When it comes to performance optimizing, caching is quite an effective way to boost the speed of your site. In this example we want to cache tweets from Twitter. We do not want to fetch data from Twitter every time the page is called because the data transfer with Twitter is quite time consuming.
1st step: Configure a cache “manifest”
These five lines go into your MyPackage/Configuration/Caches.yaml
1 2 3 4 5 |
MGApp_TweetsCache: frontend: TYPO3\FLOW3\Cache\Frontend\VariableFrontend backend: TYPO3\FLOW3\Cache\Backend\FileBackend backendOptions: defaultLifeTime: 300 |
In addition to that we also need to wire our tweetsCache to our class property tweetsCache
which we will use later in our service class.
1 2 3 4 5 6 7 8 9 |
MG\App\Service\TwitterService: properties: tweetsCache: object: factoryObjectName: TYPO3\FLOW3\Cache\CacheManager factoryMethodName: getCache arguments: 1: value: MGApp_TweetsCache |
2nd step: Dependency Injection
1 2 3 4 5 |
/** * @FLOW3\Inject * @var \TYPO3\FLOW3\Cache\Frontend\VariableFrontend */ protected $tweetsCache; |
Now we are able to access our cache with $this->tweetsCache
. I am using a service class which fetches the tweets.
3rd step: Cache it!
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 30 31 32 33 34 |
/** * Get tweets for a given stock * @param Stock $stock */ public function getTwitterFeed(Stock $stock) { $returnValue = NULL; if ($stock !== NULL) { $stockSymbol = $stock->getSymbol(); // Cache identifier $identifier = sha1($stockSymbol); if ($this->tweetsCache->has($identifier) === TRUE) { $returnValue = $this->tweetsCache->get($identifier); } else { $query = 'http://search.twitter.com/search.json?q='.$stockSymbol; $query .= self::URI_APPEND_STRING; $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_URL, $query); $result = json_decode(curl_exec($curl)); curl_close($curl); if ($result && count($result->results) > 0) { foreach($result->results as $tweet) { // Do something with the tweets $returnValue[] = $tweet; } // Write the value to the cache $this->tweetsCache->set($identifier, $returnValue); } } } return $returnValue; } |
The logic is pretty simple:
- Create a cache identifier with
1$identifier = sha1($stockSymbol); - Check if there is a valid cache entry
123if ($this->tweetsCache->has($identifier) === TRUE) {$returnValue = $this->tweetsCache->get($identifier);} - If the cache entry is invalid (because it has never been called or its lifetime ended) we need to fetch the tweets from Twitter and afterwards write the data to the cache
1$this->tweetsCache->set($identifier, $returnValue);
And this is it! Now we can track how long it takes to fetch the data from Twitter and compare it to reading from the cache. This can be achieved with AOP and I will cover this in a separate blog post.
UPDATE: Please note that every mention of FLOW3 changed to Flow since the release of TYPO3 Flow version 2.