Php 如何改进方法结构以减少参数?
在服务类中的许多方法中,我重复如下代码:Php 如何改进方法结构以减少参数?,php,laravel,refactoring,code-readability,Php,Laravel,Refactoring,Code Readability,在服务类中的许多方法中,我重复如下代码: $model->addEvent($provider->id, 'installing', 'username', 'add', 'Description of event'); $this->worker->uploadFile($provider->id, 'root', $file); 许多不同的$model将有addEvent(),这是通过trait完成的 如何将这两行代码重构成一个具有可读/难忘参数的方法 我尝
$model->addEvent($provider->id, 'installing', 'username', 'add', 'Description of event');
$this->worker->uploadFile($provider->id, 'root', $file);
许多不同的$model
将有addEvent()
,这是通过trait完成的
如何将这两行代码重构成一个具有可读/难忘参数的方法
我尝试了以下方法:
public function deploy($model, $providerId, $status, $user, $action, $file, $description = null)
{
$model->addEvent($providerId, $status, $user, $action, $description);
$this->serverWorker->uploadFile($providerId, $user, $file);
}
我不喜欢这个方法,因为它有太多的参数
用法:
例1<代码>部署($site,1,'In Queue','root','create',$file,'Installing site domain.com')
例2<代码>部署($rule,1,'队列中','root','update',$file,'更新规则')
例2
deploy($something,1,'In Queue','root','delete',$file)
您可以尝试将常见配置包装到小型可重用类中,如下所示:
public function deploy($model, FileDeployTarget $target, $description = null)
{
$model->addEvent($target->providerId, $target->status, $target->user, $target->action, $description);
$this->serverWorker->uploadFile($target->providerId, $target->user, $target->file);
}
在其他地方:
class UpdateInQueue extends FileDeployTarget {
public $status = 'In Queue';
public $action = 'update';
}
FileDeployTarget及其子代将处理其构造函数中的所有额外参数。能否提供
deploy()
用法传递到$target parm的示例?类似于deploy($rule,new UpdateInQueue($file),“update rule”)