我刚刚创建了一个从数据库中删除实体记录的操作。操作是:
public function eliminaricettaAction($id)
{
$em = $this->getDoctrine()->getManager();
$ricetta = $em->getRepository('AppBundle:Ricette')->find($id);
$em->remove($ricetta);
$em->flush();
return $this->render('adminarea/gestionericette.html.twig', array(
'base_dir' => realpath($this->container->getParameter('kernel.root_dir') . '/..'),
));
}
我得到的错误是:
警告:unlink():没有这样的文件或目录
所以我认为问题出在它本身的实体上,特别是在代码的这种和平中:
/**
* @ORM'PreRemove()
*/
public function removeImage()
{
unlink($this->getFullImagePath());
rmdir($this->getUploadRootDir());
}
我做错了什么?
您正在尝试删除不存在的文件。
在尝试删除文件之前,应确保它们存在。确认您确实从 $this->getFullImagePath()
获取了文件路径,并且该路径处的文件存在 file_exists()。
你可以这样实现它:
public function removeImage()
{
if($file = $this->getFullImagePath() && file_exists($file)) {
unlink($file);
rmdir($this->getUploadRootDir());
}
}
理想情况下,在尝试删除目录之前,您还需要检查$this->getUploadRootDir()
是否返回一个值以及该目录是否存在且不为空;但您也可以考虑是否真的有必要在每次删除文件时删除uploadRootDir
。(你是否应该完全是一个单独的问题。
首先,您应该检查该文件是否存在,@jbafford的回答对此很好。
但接下来您必须检查uploadRootDir
是否不为空,因为您无法删除不为空的目录。
$scannedDir = $this->getUploadRootDir();
if (is_dir($scannedDir)) {
$entries = scandir($entries);
if (count($entries) === 2) {
// When you have 2 entries it means you have "." and ".."
rmdir($scannedDir);
} else {
// Directory is not empty, so take care about this.
}
} else {
// Directory does not exist so you may throw an exception or do something else.
}