我正在开发一个 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/