如何正确删除与记录相关的文件

时间:2012-12-26 18:15:30

标签: php cakephp

如果新闻被删除,我需要删除与当前新闻相关的图标文件。 我看到了两种方法。

首先:

public function admin_delete ($id = null, $icon = null) {
    if ($this->request->is('get')) {
        throw new MethodNotAllowedException();
    }
    if ($this->News->delete($id)) {
        unlink(WWW_ROOT . 'img/icons/news/' . $icon);
        $this->Session->setFlash('ok!');
        $this->redirect(array('action' => 'index'));
    }
}

我需要从视图中将记录ID和文件名传递给此操作。 对我来说,它似乎有点丑陋,也可能导致与Nginx相关的问题。

第二个:

public function admin_delete ($id = null) {
    if ($this->request->is('get')) {
        throw new MethodNotAllowedException();
    }
    $icon = $this->News->read('icon', $id);
    if ($this->News->delete($id)) {
        unlink(WWW_ROOT . 'img/icons/news/' . $icon['icon']);
        $this->Session->setFlash('ok!');
        $this->redirect(array('action' => 'index'));
    }
}

但我不确定这是一个好方法,我应该使用read还是find('first')。 我希望你能以更正确的方式给我一些建议。 提前谢谢!

1 个答案:

答案 0 :(得分:0)

这些东西都不应该在控制器中。使用模型find('first')中的beforeDelete()获取记录,并将文件名保存在模型属性中。然后在afterDelete()中删除文件,您在beforeDelete()中缓存了谁的文件名。

相关问题