Reputation: 624
I have an application that runs function like SomeModel::getValue($month, $year, $departmentId)
in a loop.
getValue
creates a query and returns the result:
return self::where('department_id', '=', $department_id)
->where('year', '=', $year)
->where('month', '=', $month)
->pluck('value');
In this loop it might call the same arguments more than once. I wanted to know the best way to avoid creating a new query each time i want to get the data.
I thought about creating a static array inside the model and match against it every time getValue
is being called. If value exists in the array just return it, if not create a query.
Is my solution ok? you have any other ideas? thank you!
I'm using Laravel 4
Upvotes: 3
Views: 1930
Reputation: 10653
Static caching is the best method as long as you are ok with the implications:
Depending on the maximum size of the static array, it might be best to decide how long your cache is valid for (eg 1 minute), and push the cache to some form of cross-request cache so that you can reuse it ( see APC, Memcached, or even simple MySQL INSERT in a table) -- in all cases just save the serialized array and load it as an additional step before doing the actual computation.
Upvotes: 1