php - 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
)。有人知道更好的方法吗?
非常感谢你的帮助
解决方案
如果它适合你,没关系。关于“成功”检查部分。只需将您的调用包含在 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();
推荐阅读
- ms-word - OpenXML 跨列拆分表
- security - 基于 JWT 的身份验证/授权与 Microsoft Identity 2
- excel - 在工作簿之间复制工作表并覆盖当前工作表
- android - sdk 26 的 MediaBrowserServiceCompat startService()
- java - Bukkit - 我怎样才能让刷怪笼生成与猪不同的实体..?
- vba - 想要在 vba 中更改选定的 powerpoint 图表系列颜色
- reactjs - 将道具传递给路线
- mysql - MySQL Max unix时间戳到人类可读格式
- jquery - Flickity 幻灯片标题和幻灯片编号
- python - Python 脚本调用不同的 python 脚本,然后,从辅助脚本将字符串/结果带到主脚本