File DB Extension for Yii 2
该扩展为静态文件中声明的数据提供了 ActiveRecord 接口。这种解决方案允许通过文件来声明静态实体,如组,状态等,这些文件是在版本控制下存储的,而不是数据库。
注意:虽然该扩展允许写入数据,但不推荐使用。如果你需要复杂的本地数据存储,你应该考虑使用基于 SQLite 的常规关系数据库。
关于许可证信息,请查看 LICENSE 文件。
安装
安装该扩展的首选方式是通过 composer。
可以运行
php composer.phar require --prefer-dist yii2tech/filedb
或加
"yii2tech/filedb": "*"
到 composer.json 的 require 部分。
使用方法
这个扩展与常规的 Yii2 数据库访问层工作类似。首先你应该在你的应用程序配置中添加一个 [[\yii2tech\filedb\Connection]] 组件。
return [ 'components' => [ 'filedb' => [ 'class' => 'yii2tech\filedb\Connection', 'path' => '@app/data/static', ], // ... ], // ... ];
现在你可以通过存储在 '@app/data/static' 路径下的文件来声明实际的实体和它们的数据。默认情况下,常规的 PHP 代码文件被用于此,但你可以通过 [[yii2tech\filedb\Connection::format]] 选择不同的格式。每个实体都应该有一个对应的文件名,比如 'UserGroup','ItemStatus' 等等。所以完整的文件名应该是 '/path/to/project/data/static/UserGroup.php','/path/to/project/data/static/ItemStatus.php' 等等。每个文件都应该返回一个包含实际实体数据的数组,例如:'/path/to/project/data/static/UserGroup.php':
// file 'UserGroup.php' return [ [ 'id' => 1, 'name' => 'admin', 'description' => 'Site administrator', ], [ 'id' => 2, 'name' => 'member', 'description' => 'Registered front-end user', ], ];
在文件数据库中,每一行数据都应该有一个唯一的字段,用来识别它 -- 主键。它的名字由 [[yii2tech\filedb\Connection::primaryKeyName]] 指定。在这种情况下,你可以在行声明中省略主键,在数据数组中声明的行将作为主键值。所以前面的数据文件例子可以用下面的方式重写:
// file 'UserGroup.php' return [ 1 => [ 'name' => 'admin', 'description' => 'Site administrator', ], 2 => [ 'name' => 'member', 'description' => 'Registered front-end user', ], ];
查询数据
你可以使用 [[\yii2tech\filedb\]] 类对文件中声明的数据执行复杂的查询。这个类的工作原理类似于普通的 [[\yiiii\db\Query]],使用相同的语法。例如:
use yii2tech\filedb\Query; $query = new Query(); $query->from('UserGroup') ->limit(10); $rows = $query->all(); $query = new Query(); $row = $query->from('UserGroup') ->where(['name' => 'admin']) ->one();
使用 ActiveRecord
这个扩展的主要目的是为静态数据提供一个 ActiveRecord 接口。它通过 [[yii2tech\filedb\ActiveRecord]]和[[yii2tech\filedb\ActiveQuery]] 类来完成。特定的 ActiveRecord 类应该扩展 [[yii2tech\filedb\ActiveRecord]],并覆盖其 fileName() 方法,指定源数据文件名。例如:
class UserGroup extends \yii2tech\filedb\ActiveRecord { public static function fileName() { return 'UserGroup'; } }
注意:默认情况下 fileName() 返回自己的类基名(不含命名空间),所以如果你声明的源数据文件的名称与类基名相同,你可以忽略 fileName() 方法的覆盖。
[[/yii2tech/filedb/ActiveRecord]] 的工作原理类似于普通的 [[/yii2tech/filedb/ActiveRecord]],允许查找、验证和保存模型。它可以与其他 ActiveRecord 类建立关系,这些 ActiveRecord 类通常代表关系数据库中的实体。例如:
class UserGroup extends \yii2tech\filedb\ActiveRecord { public function getUsers() { return $this->hasMany(User::className(), ['groupId' => 'id']); } } class User extends \yii\db\ActiveRecord { public function getGroup() { return $this->hasOne(UserGroup::className(), ['id' => 'groupId']); } }
所以关系型查询可以按以下方式进行:
$users = User::find()->with('group')->all(); foreach ($users as $user) { echo 'username: ' . $user->name . "\n"; echo 'group: ' . $user->group->name . "\n\n"; } $adminGroup = UserGroup::find()->where(['name' => 'admin'])->one(); foreach ($adminGroup->users as $user) { echo $user->name . "\n"; }