参数太多了?

时间:2015-05-22 16:16:57

标签: php laravel

好的,我已经设法结束了这一次。

控制器:

  $addProperty=Property::addProperty($title,$description,$location,
                 $agent,$owner,$lat,$long,$position,$photoHolder,
                 $stars,$negatives,$adverts,$dropLink,$photosSite);

型号:

  public static function addProperty($title,$description,$location,$agent,
           $owner,$lat,$long,$position,
           $photoHolder,$stars,$negatives,
           $adverts,$dropLink,$photosSite)

问题是,不仅我有太多的参数,而且还需要传递10多个参数。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点。使用模型时,我首选的方法是为每个属性设置一个set方法。这样你就不需要一次性传递所有内容(当应用程序发展并添加/删除内容时非常有用)。

所以在一个模型中,我通常会有这样的东西:

class Property {

    private $title;
    private $description;
    private $location;

    /**
     * Creates an instance of property via a static method.
     *
     */
    public static factory()
    {
        return new Property();
    }

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

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

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

    // because the attributes in this instance are private I would also need getters

    public function getTitle()
    {
        return $title;
    }

    public function getDescription()
    {
        return $description;
    }

    public function getLocation()
    {
        return $location;
    }
}

然后,您还可以添加save()方法或其他任何您想要它的方法。

好的,所以我添加了一个名为factory的新静态方法,它允许您创建实例而无需将其分配给变量。除此之外,我已将return $this;添加到所有不返回属性的方法中。

这实际上意味着您现在可以这样做:

// create a new property
Property::factory()
    ->setTitle($title)
    ->setDescription($description)
    ->setLocation($location)
    ->save(); // if you had that function

这样做的好处是,如果你确实需要休息一下,那么以下内容也会有效。

// create a new property
$property = Property::factory()
    ->setTitle($title)
    ->setDescription($description); // this is returning the property instance `return $this`

// do some processing to get the $location value

// continue creating the new property
$property
    ->setLocation($location)
    ->save(); // if you had that function

答案 1 :(得分:2)

更好的方法是将参数作为数组传递:

$params=array(
'title'=>'title',
'other_parameter'=>'value',
);

$addProperty=Property::addProperty($params);
相关问题