方法中许多参数的替代方法?

Alternative of many parameters in method?

我想我在方法中传递了太多参数

当用户提交表单时,例如:

public function addServer(CreateRequest $request)
{
    $created = $this->server->create(
                  $request->name,
                  $request->location, 
                  $request->plan,
                  $request->php_version,
                  $request->install_mysql,
                  $request->database_name,
                  $request->do_backup,
                );
}

有时我不需要上面的所有参数,只需要几个。

在服务器中 class:

class Server {
   public function create($name, $location, $plan, $phpVersion, $installMysql, $databaseName, $doBackup) {
        $server =  $this->create($name, $location, $plan);

        if ($server) { 
        }   
   } 
}

传递一个对象(实体)会解决这个问题吗?

  1. 您可以将 $request 变量传递给 Server->createSever->createFromObject,无论您想要什么。 CreateRequest,或其他对象可以保存您需要的任何数据,稍后您检查哪个是例如。 null,哪些参数没有传递。

  2. 为每个可分离的部分创建更多方法。例如。 createServer($name, $location, $plan), setBackup(bool), setMysql($dbName),依此类推。当你创建一个服务器时,你只调用你需要的那些。

看看 builder pattern:

the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern[citation needed]. The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.

基本上,使用构建器模式,您可以保证您的对象始终正确初始化,无论是否具有可选属性。

您将创建一个额外的 ServerBuilder class,它会为服务器的每个 property/parameter 创建一个 setter,以及一个 build() 方法 returns一个Server实例。

class ServerBuilder {
    private $name = "";
    private $location = null;

    public function name($name) {
        $this->name = $name;
        return $this;
    }

    public function location($location) {
        $this->location = $location;
        return $this;
    }

    /* add other setters here .. */

    public function build() {
        // here you ensure all properties have sane values
        // if no php_version then set default etc
        return new Server($name, $location, ..., ..., etc);
    }
}

你会像这样使用它:

$builder = new ServerBuilder();
$server = $builder
    ->name("foo")
    ->location("bar")
    ->build();