检查Laravel包服务提供程序中是否存在迁移。

3

我正在编写一个Laravel套件,在其服务提供者中,该套件接收要发布的迁移列表,使用以下代码:

protected function publishMigrations(array $publishables): void
{
    // Generate a list of migrations that have not been published yet.
    $migrations = [];
    foreach($publishables as $publishable)
    {
        // Migration already exists, continuing
        if(class_exists($publishable)){
            continue;
        }
        $file = Str::snake($publishable) . '.php';
        $migrations[self::MIGRATIONS_PATH . $file . '.stub'] = database_path('migrations/'.date('Y_m_d_His', time())."_$file");
    }

    $this->publishes($migrations, 'migrations');
}

该软件包的$publishables的一个示例可能是:

$publishables = ['CreateAuthenticationsTable', 'CreateCustomersTable', 'CreateTransactionsTable'];

代码确实按预期工作,发布我打算发布的迁移,但是我正在尝试使用class_exists($publishable)行避免重复发布相同的迁移。据我所知,Laravel MediaLibrary也在使用相同的方法。但是我猜测,当发布资源时,迁移不会被加载,因为那段代码从未运行过。(class_exists始终为false)
是否有一种方法可以跟踪已经发布的迁移?这是一个自动加载的问题吗?
1个回答

3

migrationExists($mgr)函数将检查是否存在一个迁移文件在database/migrations目录中。它将循环迁移文件名并检查给定的迁移名称是否匹配。

protected function publishMigrations()
    {
        if (!$this->migrationExists('create_admins_table')) {
            $this->publishes([
              __DIR__ . '/database/migrations/create_admins_table.php.stub' => database_path('migrations/' . date('Y_m_d_His', time()) . '_create_admins_table.php'),
              // you can add any number of migrations here
            ], 'migrations');
            return;
        }
    }



protected function migrationExists($mgr)
    {
        $path = database_path('migrations/');
        $files = scandir($path);
        $pos = false;
        foreach ($files as &$value) {
            $pos = strpos($value, $mgr);
            if($pos !== false) return true;
        }
        return false;
    }

1
感谢您提供这个函数。您有任何想法为什么class_exist返回false吗? - Mike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接