参数太多?

马基斯

好的,我设法结束了这一件事。

控制器:

  $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个左右的参数。

有什么建议吗?

挖掘机世界

您可以通过多种方式来执行此操作。我在使用模型时的首选方式是为每个属性设置一个设置方法。这样,您无需一次全部传递所有内容(随着应用程序的发展和添加/删除内容非常有用)。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章