Reputation: 443
I am confused as to how to use the cache in Laravel. I can either use the Cache facade and do something like …
use Cache;
public function someMethod()
{
Cache::remember('users', 60 , function() {
return DB::table('users')->get();
});
}
Or I could use something like this …
use Illuminate\Contracts\Cache\Repository;
protected $cache;
public function __construct(Repository $repository)
{
$this->cache = $repository;
}
public function someMethod()
{
$this->cache->remember('users', 60 , function() {
return DB::table('users')->get();
});
}
Both will implement the same method remember from vendor/laravel/framework/src/Illuminate/Cache/Repository.php
Repository class which implements vendor/laravel/framework/src/Illuminate/Contracts/Cache/Repository.php
which I have included in the second method.
As per Laravel docs:
The
Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository
contracts provide access to Laravel's cache services. The Factory contract provides access to all cache drivers defined for your application. The Repository contract is typically an implementation of the default cache driver for your application as specified by your cache configuration file.However, you may also use the Cache facade, which is what we will use throughout this documentation. The Cache facade provides convenient, terse access to the underlying implementations of the Laravel cache contracts.
So can I conclude that both the approach are same. The Cache Facade provides me a cleaner implementation, that's it.
Upvotes: 2
Views: 275
Reputation: 57683
You would get the same result in your application. It's the same but not the same.
In your second approach you are using dependency injection. Which makes it easier to write tests for your class. This way you get a better maintainable application.
Have a deeper look at dependency injection. Here is a nice article: Dependency Injection with Laravel’s IoC.
Upvotes: 1