在Laravel中实现与Cache :: disk('x')类似的功能 [英] Implementing similar functionality to Cache::disk('x') in Laravel
问题描述
这只是我要寻找的解决方案的一个普遍问题.
This is just a general question around a solution I'm trying to find.
我可能有许多提供相同类型服务的提供商,我需要一种能够拥有默认服务的方法,然后还需要手动调用切换器方法来更改它们.
I have potentially many providers of the same type of service and I need a way to be able to have a default, but then also manually call a switcher method to change them.
当前,我已经通过配置设置将接口绑定到实现,并且效果很好-但这意味着我只能为每种服务类型支持一个活动的提供程序.
Currently, I've bound an Interface to an Implementation via configuration settings and this works well - but it means I can only support one active provider per type of service.
我注意到Cache :: disk()方法确实是我想要的,但是我不确定应该在哪里定义这种类型的switch方法.
I noticed the Cache::disk() method is really what I'm looking for, but I'm not sure where this type of switch method should be defined.
当前:
interface IProvider {
public function getServiceInfo($args);
public function setServiceInfo($args);
}
class GoldService implements IProvider {
// implementation of the two interface methods
}
class SilverService implements IProvider {
}
// ProviderServiceProvider
public function register()
{
$this->app->bind(
App/IProvider,
App/GoldService
);
}
// Controller
public function getServiceInfo(Service $serviceId)
{
$provider = $app->make('App/IProvider');
$provider->getServiceInfo($serviceId);
}
想要.
// What I want to be able to do
public function getServiceInfo(Service $serviceId)
{
// Using a facade
if ($serviceId > 100)
{
Provider::getServiceInfo($serviceId);
}
else
{
Provider::switch('SilverService')
->getServiceInfo($serviceId);
}
}
我知道我对Facade提出了附加要求-不确定我是否在这里混淆了Contracts/Fades-但本质上我希望接口强制执行实例方法,但是Facade可以方便地访问实例
I know I've thrown in an additional requirement there of the Facade - not sure if I've confused Contracts/Facades here - but essentially I want the interface to enforce the instance methods, but Facade for easy access to the instances.
并不是在这里真正寻找代码-这将很容易.我只是不确定我是否真的想过这个,并正在朝着正确的方向寻找微动.
Not really looking for code here - that'll be the easy part. I'm just not sure I've really grok'd this and looking for a nudge in the right direction..
推荐答案
使用接口确保服务实现您所需的方法是合理的.
Using an interface to ensure a service implements the methods you require makes sense.
但是要根据对象实例的属性使用其他服务;对我来说,这听起来更像是Factory
模式.
But with regard to using a different service based on the properties of an object instance; that sounds more like the Factory
pattern to me.
http://www.phptherightway.com/pages/Design-Patterns.html
这篇关于在Laravel中实现与Cache :: disk('x')类似的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!