如何使用新的自我构造 php 加载数据



我不能使用此结构将数据加载到属性,我在转储中收到空

<?php
namespace AppDomainGood;

class GoodDto
{
public $name;
public $articul;
public $price;
public $type;
public $qnt;
public $discount;
public $category;
public $description;
public $description2;
public $color;

public function load($data)
{
$this->name = $data['name'];
$this->articul = $data['artikul'];
$this->price = $data['price'];
$this->type = (isset($data['type'])) ? $data['type'] : null;
$this->qnt = $data['count'];
$this->discount = $data['spinner-decimal'];
$this->category = $data['id_cat'];
$this->description = $data['editor1'];
$this->description2 = '';
$this->color = $data['color'];
//$this->user_id = Auth::user()->id;
}
public static function fromRequest($request)
{
dump('inp=>',(new self ())->load($request->input()));
return (new self ())->load($request->input());
}
}

请向我解释为什么我收到 null 而 request->input() 是一个数组,我从另一个地方调用它

$dto=GoodDto::fromRequest($request);

方法链,返回链中的最后一个返回值。其他返回用于调用链中的下一个链接。

(new self ())->load()

所以load()需要返回$this

public function load($data)
{
...
return $this; 
}

目前它返回null,这就是它返回 null 的原因。

看到您没有从构造函数中保存实例,而是通过将它包含在(....)中来将其传递给 load。 通过传递它,我的意思是您在从构造函数返回时调用 load 方法。

您可以像这样测试:

class foo{
function load(){
return $this;//return this
}
}
var_dump((new foo)->load());
class bar{
function load(){
//return null
}
}
var_dump((new bar)->load());

输出

//return this
object(foo)#1 (0) {
}
//return null
NULL

沙盒

上面示例中的第二个类class bar,本质上就是您正在做的事情。

一开始忘记向下滚动您的帖子...哈哈......所以我不得不更新我的答案。

奖金

您还可以像这样简化加载代码:

public function load($data)
{
foreach($data as $prop=>$value){
if(property_exists($this,$prop)) $this->$prop = $value;
}
return $this;
}

这样,如果您添加新属性,则不必再次编辑 load 方法,只需将数组元素命名为与类属性相同的名称即可。 如果需要,如果属性不存在,您甚至可以抛出错误,方法是向条件添加else等......

就个人而言,当我这样做时,我更喜欢调用这样的 set 方法:

//eg. $data = ['foo' => '2019-06-16']
public function load(array $data)
{
foreach($data as $prop=>$value){
$method = 'set'.$prop;  //$method = 'setfoo' using the example above
if(method_exists($this,$method )){
$this->$method($value); //calls 'setfoo' with '2019-06-16'
}else{
throw new Exception('Unknown method '.$method);
}
}
return $this;
}
public function setFoo($date){
$this->foo = new DateTime($date);
}

然后,您可以对数据等应用一些转换... PHP 方法名称不区分大小写。 您甚至可以通过首先检查方法然后检查属性然后抛出错误等来组合它们......

干杯。

最新更新