我们在编写PHP方法时,通常有若干个参数,就像下面的代码:
Class Book
{
public function create($name, $cateId, $author)
{
$params = [
'name' => $name,
'cateId' => $cateId,
'author' => $author
];
}
}
没有任何问题。
但是,随着业务的发展,参数可能会不断增加。就像上面的例子,创建一本书刚开始只有name/cateId/author三个参数,慢慢可能就变成了下面这样:
Class Book
{
public function create($name, $cateId, $author, $year, $price, $publish, $country, $language)
{
$params = [
'name' => $name,
'cateId' => $cateId,
'author' => $author,
'year' => $year,
'price' => $price,
'publish' => $publish,
'country' => $country,
'language' => $language,
];
}
}
It works well!但是看起来总觉得不太优雅,当你调用这个方法的时候,鬼才知道参数的顺序是怎么样的!
如何优化呢?我们可以尝试把参数对象化。请看下面的代码:
class BookModel
{
protected $name;
protected $cateId;
protected $author;
protected $year;
protected $price;
protected $publish;
protected $country;
protected $language;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getCateId()
{
return $this->cateId;
}
public function setCateId($cateId)
{
$this->cateId = $cateId;
}
public function getAuthor()
{
return $this->author;
}
public function setAuthor($author)
{
$this->author = $author;
}
public function getYear()
{
return $this->year;
}
public function setYear($year)
{
$this->year = $year;
}
public function getPrice()
{
return $this->price;
}
public function setPrice($price)
{
$this->price = $price;
}
public function getPublish()
{
return $this->publish;
}
public function setPublish($publish)
{
$this->publish = $publish;
}
public function getCountry()
{
return $this->country;
}
public function getLanguage()
{
return $this->language;
}
public function setLanguage($language)
{
$this->language = $language;
}
}
上面定义了一个BookModel类,包含了一些属性。然后我们对create方法进行改造,要求它的参数为BookModel类。由于BookModel的数据结构是明确的,使用起来非常方便。create方法调整后:
Class Book
{
public function create(BookModel $bookModel)
{
$params = [
'name' => $bookModel->getName(),
'cateId' => $bookModel->getCateId(),
'author' => $bookModel->getAuthor(),
'year' => $bookModel->getYear(),
'price' => $bookModel->getPrice(),
'publish' => $bookModel->getPublish(),
'country' => $bookModel->getCountry(),
'language' => $bookModel->getLanguage(),
];
}
}
看,面向对象编程的优势在这里凸显出来了!