2017-06-07 23 views
1

在服务种类很多方法,我重复这样的代码:如何改进减少参数的方法结构?

$model->addEvent($provider->id, 'installing', 'username', 'add', 'Description of event'); 

$this->worker->uploadFile($provider->id, 'root', $file); 

许多不同$model会有addEvent()这是通过特征来完成。

如何将这两行重构为可读/难记参数的方法?

我曾尝试以下:

public function deploy($model, $providerId, $status, $user, $action, $file, $description = null) 
{ 
    $model->addEvent($providerId, $status, $user, $action, $description); 

    $this->serverWorker->uploadFile($providerId, $user, $file); 
} 

我不喜欢这种方法,有太多的PARAMS什么。

用法:

如1 deploy($site, 1, 'In Queue', 'root', 'create', $file, 'Installing Site domain.com')

如2. deploy($rule, 1, 'In Queue', 'root', 'update', $file, 'Updating Rule')

如2. deploy($something, 1, 'In Queue', 'root', 'delete', $file)

回答

1

你可以尝试包裹常见配置成小的可重用类,像这样:

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); 
} 

而且别的地方:

FileDeployTarget和后裔会处理他们所有的构造函数的额外参数。

+0

你可以提供'deploy()'用法传递给$ target parm的例子吗? –

+1

类似'deploy($ rule,new UpdateInQueue($ file),“Updating Rule”)' –