我正在从事一个网络游戏项目,其中有项目的概念.
用户可以在其库存中拥有的物品的各个实例存储在数据库中.这些行中的每一行都有一个名为item_base
的列,该列在代码中用于获取有关项目的详细信息.示例:
unique_item_id | player_id | item_base |
---|---|---|
3345346 | 43455 | ITEM_ONE |
3856739 | 97212 | ITEM_TWO |
我的ItemBase
个班级:
class ItemBase {
public $name;
public $type;
public $action;
public function __construct(string $name, ItemType $type, callable $action) {
$this->name = $name;
$this->type = $type->value;
$this->action = $action();
}
}
ItemType
枚举只是一个标准的枚举,它返回一个字符串以防止输入错误.
我希望在代码库中"注册"我的所有项目库,而不是在数据库中注册它自己的表,因为我想防止额外的查询.每个项库还有一个函数($action
),用于确定在使用项时应该执行哪些代码,并且我避免将PHP直接放入数据库中.
创建新的项目库将如下所示:
new ItemBase("Item One", ItemType::FOOD, function() {
//Code to execute when the function is called
});
My goal is to be able to reference item bases with something like 100.,然后我可以使用ItemBase::ITEM_ONE->name
或通过构造传递的其他变量.
解决这一问题的最佳方式是什么?能够定义类型(IDE也支持类型完成)比使用$ARRAY[‘STRING’]查找更可取.由于枚举不能由对象支持,我能对注册表类型类做些什么吗?
我try 创建一个包含所有ItemBase的类,然后注册每个类,如下所示:
public static function ITEM_ONE() {
return new ItemBase("Item One", ItemType::FOOD, function() {
//Code to execute when the function is called
});
这允许我使用ItemBase::ITEM_ONE()
,但我正在寻找一种方法,它不需要为游戏中的每个物品库提供函数.