SummerRain2021
2021-12-12 13:04
采纳率: 0%
浏览 7

Laravel 入库写法讨论

很简单的文章提交功能,
平时入库的写法,我是这么写的:

foreach ($_POST['ArticelData'] as $item) {
    $model = new Articel();
    $model->Title = $item['Title'];
    $model->Content = $item['Content'];
    $model->Image = $item['Image'];
    $model->save();
 }

但是今天看到有这么写的:

主model类里这么写:

$InsertData = [];
foreach ($_POST['ArticelData'] as $item) {
   $model = new ArticelFilter($item);
   $model->setTitle($model->getTitle());
   $model->setContent($model->getContent());
   $model->setImage($model->getImage());
   $InsertData[] = $model->toArray();
   }
Articel::insert($InsertData);

ArticelFilter的Model:


protected $Title;
protected $Content;
protected $Image;
  public function setTitle()
  {
      return $this->Title;
  }
  public function getTitle($Title)
  {
      $this->Title = $Title;
  }
  public function setContent($Content):  
  {
      $this->Content = $Content;
  }
  public function getContent()
  {
      return $this->Content;
  }
  public function setImage($Image): 
  {
      $this->Image = $Image;
  }
  public function getImage()
  {
      return $this->Image;
  }

这些set和get,在基类用这个构造方法实现:

public function __call($name, $params)
{
    $function_type = substr($name, 0, 3);
    if (in_array($function_type, array('get', 'set'))) {
        $property = lcfirst(substr($name, 3));
        if (property_exists($this, $property)) {
            switch ($function_type) {
                case 'get':
                    return $this->$property;
                case 'set':
                    $this->$property = $params[0];
            }
        }
    }
}

请教一下各位,这么写的原理是什么,好处是什么?
感觉很多SDK都是这么写的, 这属于一种设计模式吗?

1条回答 默认 最新

相关推荐 更多相似问题