【问题标题】:How to improve method structure to reduce params?如何改进方法结构以减少参数?
【发布时间】:2017-06-07 22:20:03
【问题描述】:

在服务类的许多方法中,我重复这样的代码:

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

我不喜欢这种方法的参数太多。

用法:

例如 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)

【问题讨论】:

    标签: php laravel refactoring code-readability


    【解决方案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);
    }
    

    还有其他地方:

    class UpdateInQueue extends FileDeployTarget {
        public $status = 'In Queue';
        public $action = 'update';
    }
    

    FileDeployTarget 和后代将在其构造函数中处理所有额外参数。

    【讨论】:

    • 你能提供deploy()使用传递给$target parm的例子吗?
    • 类似deploy($rule, new UpdateInQueue($file), "Updating Rule")
    猜你喜欢
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多