[英]How can I efficiently structure this code in Laravel?
我有一个名为Sharer
的类,该类在Construct方法中接受Service
接口。 Service
可以是FacebookService
或TwitterService
等。 每个Service
类都有一个post
方法,该方法使用自己的连接(在此示例中为facebook,twitter)发布传递给该方法的任何数组数据。
现在, Sharer
类在将数据发送到该service
的post方法之前对其进行normalizes
。 通过规范化,它检查我们发送给该post
方法的对象是简单数组还是Model
类。 Model
可以是“ Project
模型,“ Image
模型或“ Video
模型等。
如果是模型类,那么它将调用该特定模型的转换器。 Transformers
只是帮助程序类,它们接受模型实例,并且它们有两种方法-在这种情况下为facebook
和twitter
。 每个方法都返回一个特定于连接的格式化数组。
因此,例如, facebook
方法从模型中获取必需的字段(将其发布到facebook上),并将该数组发送回去。 twitter方法对twitter的必填字段执行相同的操作。
现在,我有点困扰,是在转换器类上调用该特定方法。 我想做这样的事情:
if(we are sharing on facebook) {
then call the facebook method
}
if(we are sharing on twitter) {
then call the twitter method
}
但显然我想以某种方式使其具有动态性,并且不包含这些if语句。 有什么更好的方法呢?
我这样做解决了:
$method = $this->resolveMethodToCall();
protected function resolveMethodToCall()
{
$reflection = new ReflectionClass($this->service); // service being either a FacebookService class or TwitterService
$shortName = $reflection->getShortName();
return strtolower(str_replace('Service', '', $shortName));
}
可能不是最好的解决方案,但是效果很好,在此之后,我要检查已解决的方法是否确实存在于转换器类中,如果不存在,则抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.