首页 > 解决方案 > Symfony - 重置数据库的最佳实践

问题描述

我正在开发一个 Symfony 4.2 项目,并且我正在寻找最佳实践,以在管理员需要通过后台中的按钮执行此操作时实现数据库的重置。

解释 :

该项目是一个临时活动网站。这意味着,人们只会访问该网站一天/一周,然后该网站就关闭了。例如,在篮球比赛期间观众进入体育场的网站。

比赛结束后,管理员希望通过一个按钮重置比赛期间发送的所有数据。

现在我这样做了,但我不知道这是否是生产环境中的更好方法。

我创建了一个在构造函数中获取 KernelInterface 的服务:

public function resetDB() {

    $application = new Application($this->kernel);
    $application->setAutoExit(false);

    $input = new ArrayInput([
        'command'   => 'doctrine:schema:drop',
        '--force' => true
    ]);

    $output = new BufferedOutput();
    $application->run($input, $output);

    $responseDrop = $output->fetch();

    if (strpos($responseDrop, 'successfully') !== false) {
        $input = new ArrayInput([
            'command'   => 'doctrine:schema:create',
        ]);

        $application->run($input, $output);

        $responseCreate = $output->fetch();

        if (strpos($responseCreate, 'successfully') !== false)
            return new Response();
    }

    return new \ErrorException();
}

首先,在生产环境中这样做好吗?(其他管理员在进行此操作时不会使用该网站)

其次,我对我用来检查操作是否成功完成的方法不是很满意(strpos($responseCreate, 'successfully') !== false)。有人知道更好的方法吗?

非常感谢你的帮助

标签: phpsymfonysymfony4symfony-console

解决方案


如果它适合你,没关系。关于“成功”检查部分。只需将您的调用包含在 try-catch 块中并检查异常。如果没有抛出异常,则假设它确实执行成功。

$application = new Application($this->kernel);
$application->setAutoExit(false);

try {
    $application->run(
        new StringInput('doctrine:schema:drop --force'),
        new DummyOutput()
    );

    $application->run(
        new StringInput('doctrine:schema:create'),
        new DummyOutput()
    );

    return new Response();
} catch (\Exception $exception) {
    // don't throw exceptions, use proper responses
    // or do whatever you want

    return new Response('', Response::HTTP_INTERNAL_SERVER_ERROR);
}

PostgreSQL 在 DDL 事务方面是否足够好?然后强制交易:

$application = new Application($this->kernel);
$application->setAutoExit(false);

// in case of any SQL error
// an exception will be thrown
$this->entityManager->transactional(function () use ($application) {
    $application->run(
        new StringInput('doctrine:schema:drop --force'),
        new DummyOutput()
    );

    $application->run(
        new StringInput('doctrine:schema:create'),
        new DummyOutput()
    );
});

return new Response();

推荐阅读