安装
composer require lulco/phoenix
composer require fakerphp/faker
创建配置和目录
先创建配置文件
然后项目根目录新建配置文件phoenix.php
<?php
return [
'migration_dirs' => [
'm' => __DIR__ . '/database/m',
's' => __DIR__ . '/database/s',
],
'environments' => [
'local' => [
'adapter' => 'mysql',
'host' => 'localhost',
'port' => 3306, // optional
'username' => 'root',
'password' => 'root',
'db_name' => 'blog',
'charset' => 'utf8mb4',
],
'production' => [
'adapter' => 'mysql',
'host' => 'production_host',
'port' => 3306, // optional
'username' => 'user',
'password' => 'pass',
'db_name' => 'blog',
'charset' => 'utf8mb4',
],
],
'default_environment' => 'local',
'log_table_name' => 'phoenix_log',
];
再创建配置中指定的目录
指令
创建
vendor\bin\phoenix create Goods m
就会生成默认的迁移文件,up
是执行迁移执行的方法,down
是回退的时候执行的方法
<?php
use Phoenix\Migration\AbstractMigration;
class Goods extends AbstractMigration
{
protected function up(): void
{
$this->execute(
"create table `goods`
(
id int not null auto_increment primary key,
username varchar(10) comment '用户名',
password varchar(32) comment '密码',
phone varchar(11) comment '注册手机号',
email varchar(50) unique comment '邮箱',
last_login_ip char (15) comment '最后登录IP地址',
last_login_time timestamp null comment '最后登录的时间',
active tinyint not null default 0 comment '激活状态 0:未激活 1:激活',
create_time timestamp null comment '创建时间',
update_time timestamp null comment '更新时间',
delete_time timestamp null comment '删除时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
);
}
protected function down(): void
{
$this->execute(
"DROP TABLE `goods`;"
);
}
}
执行
vendor\bin\phoenix migrate --dir m
此时一张数据库就创建好了。
回退
此时你想返回上一步
vendor\bin\phoenix rollback --dir m
执行后,数据表将会被删除
清空
vendor\bin\phoenix cleanup
填充
phoneix
中没有填充这个功能,但是可以把填充当作是迁移文件来执行,其中使用到了faker
帮助我们填充模拟数据
<?php
use Phoenix\Migration\AbstractMigration;
class UserSeeder extends AbstractMigration
{
protected function up(): void
{
$faker = Faker\Factory::create('zh_CN');
$data = [];
for ($i = 0; $i < 100; $i++) {
$data[] = [
'username' => $faker->randomLetter . $faker->unique()->randomNumber(5, true),
'password' => $faker->password,
'phone' => $faker->phoneNumber,
'email' => $faker->email,
'last_login_ip' => $faker->ipv4,
'last_login_time' => date('Y-m-d H:i:s'),
'active' => [0, 1][rand(0, 1)],
'create_time' => date('Y-m-d H:i:s'),
'update_time' => date('Y-m-d H:i:s'),
'delete_time' => date('Y-m-d H:i:s'),
];
}
//清空表
$this->table('lu_user')->truncate();
//插入数据
$this->insert('lu_user',$data);
//更新数据,方便我们测试
$this->update('lu_user',['username'=>'admin','password'=>'admin123'],['id'=>1]);
}
protected function down(): void
{
$this->table('lu_user')->truncate();
}
}