Load and cache data for the entire application

Which is the right way to load and cache data for the whole application? Directly in application/config/app.php or in a service provider?

For a single block I would extend the controller with such a function

public function getData()
	$expensiveCache = $this->app->make('cache/expensive');
	$cacheItem = $expensiveCache->getItem('Localize/list');
	if ($cacheItem->isMiss()) {
		@$JSON = file_get_contents("https://raw.githubusercontent.com/benoitvallon/100-best-books/master/books.json");
		if($JSON == FALSE) {
			echo 'json empty';
			return '';
		$data = json_decode($JSON);
	else {
		$data = $cacheItem->get();
	return $data;

I don’t think there’s a ‘correct’ way here, it might just come down to where it’s most logical to actually trigger the fetching and caching.

If it’s output from a block, within the block controller makes sense.
If it’s a particular page type, or single page, that page’s controller
If it’s a common function that needs to be accessed from lots of places, I’d probably put the code in a custom package (or at least in a package related to where I need the data), in a custom class, maybe a static function.

Personally I try to avoid adding things in the /application directory if they’re not just overrides or minor customisations, and instead look to put that code in packages.

1 Like

Thanks alot for your advice. I will probably choose a seperate custom package.