如何改进方法结构以减少参数?
How to improve method structure to reduce params?
在服务的许多方法中类我重复这样的代码:
$model->addEvent($provider->id, 'installing', 'username', 'add', 'Description of event');
$this->worker->uploadFile($provider->id, 'root', $file);
许多不同的 $model
将具有 addEvent()
,这是通过特征完成的。
如何将这两行重构为具有 readable/memorable 个参数的方法?
我试过以下方法:
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.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)
您可以尝试将通用配置包装成小型可重用 类,如下所示:
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 和后代将处理其构造函数中的所有额外参数。
在服务的许多方法中类我重复这样的代码:
$model->addEvent($provider->id, 'installing', 'username', 'add', 'Description of event');
$this->worker->uploadFile($provider->id, 'root', $file);
许多不同的 $model
将具有 addEvent()
,这是通过特征完成的。
如何将这两行重构为具有 readable/memorable 个参数的方法?
我试过以下方法:
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.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)
您可以尝试将通用配置包装成小型可重用 类,如下所示:
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 和后代将处理其构造函数中的所有额外参数。