为以后的实现实现抽象基础模型:
abstract class AbstractNode extends Model
{
use HasFactory;
protected static function boot(): void
{
static::creating(static function (self $model) {
//
});
static::deleting(static function (self $model) {
//
});
}
abstract public function getTitle(): string;
abstract public function getAllowedChildren(): ?array;
}
然后实例化这个基础模型:
class Region extends AbstractNode
{
protected $fillable = [
'name', // Region name
];
public function getTitle(): string
{
return 'Region';
}
public function getAllowedChildren(): ?array
{
return null;
}
}
使用
Region
类作为 $region = new Region();
以致命错误结束:
Undefined array key "App\Models\Region"
当我将 Region 编码为扩展模型而不是 AbstractNode 时 - 一切正常。
可以使用抽象模型类吗?
完全支持在 Laravel 中使用抽象模型,但您必须小心管理像
HasFactory
这样的特征,以避免工厂解析出现问题。通过显式定义工厂或仔细管理特征的使用,您可以成功使用抽象模型类。
希望对你有帮助:
在具体类中显式定义工厂
class Region extends AbstractNode
{
use HasFactory; // Use this trait only if factory functionality is needed
protected $fillable = ['name'];
public function getTitle(): string
{
return 'Region';
}
public function getAllowedChildren(): ?array
{
return null;
}
protected static function newFactory()
{
return \Database\Factories\RegionFactory::new();
}
}
确保正确的启动方法处理
abstract class AbstractNode extends Model
{
protected static function boot(): void
{
parent::boot(); // Ensure the parent's boot method is called
static::creating(static function (self $model) {
// Add custom logic for creating event
});
static::deleting(static function (self $model) {
// Add custom logic for deleting event
});
}
abstract public function getTitle(): string;
abstract public function getAllowedChildren(): ?array;
}
始终在抽象类的
parent::boot()
方法中调用boot
,以确保父级的boot方法逻辑被执行。
记录您的抽象模型
/**
* Abstract base class for hierarchical nodes.
*
* Provides common functionality for all nodes in the hierarchy,
* such as booting events and shared logic.
*
* @method static creating(\Closure $callback)
* @method static deleting(\Closure $callback)
*/
abstract class AbstractNode extends Model
{
// ...
/**
* Get the title of the node.
*
* @return string
*/
abstract public function getTitle(): string;
/**
* Get the allowed child node types.
*
* @return array|null
*/
abstract public function getAllowedChildren(): ?array;
}