【发布时间】:2015-07-13 10:33:46
【问题描述】:
我正在尝试以这样一种方式构建我的模型,即始终有一个 baseUser 具有每个用户需要的基本功能。
然后在环境 a) 中,我可能想以不同于环境 b) 的方式扩展此用户。
我的基类:
<?php
namespace App\Libraries;
use Illuminate\Database\Eloquent\Model;
abstract class basicUser extends model
{
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = array('name', 'email');
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('remember_token', 'password');
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $guarded = array();
public function ratings()
{
return $this->hasMany('\App\Rating');
}
/*========== Override class variable declarations for children. ==========*/
protected function setFillableAttribute($value)
{
if (count(class_parents($this)) > 1) # Check if there is more than one parent, they all need the Eloquent model.
{
# Yes, there are parents. We need to combine the parent $fillable with the extra ones in the child.
$this->fillable = array_unique(array_merge($this->fillable,$value));
}
else
{
# No parents except Eloquent model.
$this->fillable = $value;
}
}
protected function setHiddenAttribute($value)
{
if (count(class_parents($this)) > 1) # Check if there is more than one parent, they all need the Eloquent model.
{
# Yes, there are parents. We need to combine the parent $hidden with the extra ones in the child.
$this->hidden = array_unique(array_merge($this->hidden,$value));
}
else
{
# No parents except Eloquent model.
$this->hidden = $value;
}
}
protected function setGuardedAttribute($value)
{
if (count(class_parents($this)) > 1) # Check if there is more than one parent, they all need the Eloquent model.
{
# Yes, there are parents. We need to combine the parent $guarded with the extra ones in the child.
$this->guarded = array_unique(array_merge($this->guarded,$value));
}
else
{
# No parents except Eloquent model.
$this->guarded = $value;
}
}
}
我的基类中的 set...Attribute() 方法背后的想法是,如果孩子想要添加到 $fillable、$hidden 或 $guarded,则不会重置父值。
<?php
namespace App\Libraries;
use App\Libraries\basicUser;
class User extends basicUser
{
protected $fillable = array('extra');
protected $hidden = array();
protected $guarded = array();
}
现在我真正想要的是让我的$u = user::find(1); 拥有密码和remember_token 被隐藏......但受保护的$hidden 似乎被覆盖了。
这种结构甚至可能吗?我是否以错误的方式接近它?
【问题讨论】:
标签: php laravel laravel-5 eloquent