symfony7自定义服务:
services:
App\SomeService:
arguments:
$customCache: '@cache.custom_cache'
解释:
services: 这是 Symfony 服务配置的主要部分。
App\SomeService: 这指定了我们正在配置的服务类。这里是 App\SomeService 类。
arguments: 这部分用于指定服务构造函数的参数。
$customCache: '@cache.custom_cache'
$customCache 是构造函数中参数的名称。
'@cache.custom_cache' 是一个服务引用。@ 符号表示这是对另一个服务的引用,而不是普通的字符串。
这个配置的作用是:当 Symfony 的依赖注入容器创建 App\SomeService 的实例时,它会将 cache.custom_cache 服务注入到构造函数的 $customCache 参数中。
你的服务类可能看起来像这样:
phpCopynamespace App;
use Symfony\Contracts\Cache\CacheInterface;
class SomeService
{
private $cache;
public function __construct(CacheInterface $customCache)
{
$this->cache = $customCache;
}
// 使用 $this->cache 的其他方法...
}
有了这个配置,你可以在应用的任何地方使用这个服务,而不需要手动创建缓存对象:
phpCopyclass SomeController
{
public function someAction(App\SomeService $someService)
{
// $someService 已经被注入了正确的缓存实例
// 可以直接使用
}
}
优点:
解耦:你的 SomeService 类不需要知道具体使用哪个缓存服务,这由配置决定。
灵活性:你可以轻松地在不同环境中切换不同的缓存实现,只需更改配置文件。
测试友好:在单元测试中,你可以轻松地注入一个模拟的缓存服务。
