PHP/Laravel不确定调用什么代码来创建模型的新实例



我对php比较陌生。在我的项目中,正在像这样创建一个模型实例:

$blah = new SomeModelName(['arg1' => $arg1, 'arg2' => $arg2, 'arg3' => $arg3]);

我认为当使用new关键字调用模型中的__costruct函数时。好吧,该模型将不同的类一直扩展到位于IlluminateDatabaseEloquentModel.php

我已经追溯到基Model.php类,在所有子类中,没有__construct函数可以覆盖基类Model.php类中的__construct,所以我认为IlluminateDatabaseEloquent中的基Model.php类中的__construct函数是应该调用的。但是,我在基Model.php类中放置了一个调试语句,并且它没有输出,因此基Model.php中的__construct似乎不是正在调用的__construct函数。

谁能指出我正确的方向,在初始化类时在哪里可以找到正在调用的__construct函数?

用户定义的模型继承自IlluminateDatabaseEloquentModel,这是一个定义此方法的抽象类:

/**
* Create a new Eloquent model instance.
*
* @param  array  $attributes
* @return void
*/
public function __construct(array $attributes = [])
{
$this->bootIfNotBooted();
$this->initializeTraits();
$this->syncOriginal();
$this->fill($attributes);
}

请注意,该参数以类型提示array。如果向函数传递其他内容,则会发生TypeError,并且不会运行。

您可以在自己的模型上创建一个构造函数,该构造函数使用提供的参数执行某些操作。例如:

<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Widget extends Model
{
private $foo;
private $bar;
public function __construct($arg1, $arg2)
{
$this->foo = $arg1;
$this->bar = $arg2;
parent::__construct();
}
}
$widget = new Widget($arg1, $arg2);

但更典型的是使用二传手或直接传递属性:

<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Widget extends Model
{
private $foo;
private $bar;
}
$attributes = ["foo"=>$arg1, "bar"=>$arg2];
$widget = new Widget($attributes);

我不知道你想做什么。但是当你看Model类时,你会看到神奇的方法。这是那constructor发生的事情.

public function __construct(array $attributes = [])
{
$this->bootIfNotBooted();
$this->initializeTraits();
$this->syncOriginal();
$this->fill($attributes);
}

你会看到有$attributes参数。它将帮助您通过质量分配启动对象(但您必须先写入$fillable属性(。

因此,如果要创建新对象,则只需编写new Company(['name' => "Hilman Corp.", 'city' => "Mojokerto"])即可。这是Company类。

class Company extends Model
{
protected $fillable = ['name','city'];
}

也许您想将constructor的逻辑添加到大写的第一个字母中。您可以轻松修改代码,如下所示。

class Company extends Model
{
protected $fillable = ['name','city'];
public function __construct(array $attributes=[])
{
$attributes['city'] = ucfirst($attributes['city']);
parent::__construct($attributes);
}   
}

我的建议是不要重写一些可能破坏Laravel对待班级的方式的东西。以后升级Laravel版本时可能会给您带来痛苦。

最新更新