php - Symfony - 重置数据库的最佳实践

标签 php symfony symfony4 symfony-console

我正在开发一个 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)。有人知道更好的方法吗?

非常感谢您的帮助

最佳答案

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

$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();

关于php - Symfony - 重置数据库的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56479271/

相关文章:

Symfony2 选择学说中的一列

php - 在 Symfony kernel.controller 事件中,ControllerEvent::getController() 的返回类型是什么?

php - Symfony 路由组件不路由 url

php - Opcache 预加载并缺少 App_KernelProdContainer.preload.php

PHP 和 Elasticsearch 在返回的对象中包含分数/相关性

php - 如何在 PHPExcel 图表中发送静态工作表数据

php - 无法从 EC2 WordPress 站点连接到 Amazon RDS

php - Symfony 从数据库生成实体

php - 这个无法访问的区域是否可以仅使用 CSS 进行链接?

php - 交响乐 4 : You have requested a non-existent service