我对php比较陌生。在我的项目中,正在像这样创建一个模型实例:
$blah = new SomeModelName(['arg1' => $arg1, 'arg2' => $arg2, 'arg3' => $arg3]);
我认为当使用new
关键字调用模型中的__costruct
函数时。好吧,该模型将不同的类一直扩展到位于IlluminateDatabaseEloquent
的Model.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版本时可能会给您带来痛苦。