普通网友 2021-12-12 13:04 采纳率: 0%
浏览 11

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条回答 默认 最新

  • 小罗的小刘 2021-12-16 11:08
    关注

    维护性把,不过我也是第一种写法

    评论

报告相同问题?

问题事件

  • 创建了问题 12月12日

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP