2012-12-26 31 views
0

如果刪除了新聞,我需要刪除與當前新聞相關的圖標文件。 我看到2種方法。如何正確刪除與記錄相關的文件

第一:

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')); 
    } 
} 

但我不知道它是一個不錯的方法,我應該使用readfind('first')。 我希望你能給我一些關於如何以更正確的方式做到的建議。 在此先感謝!

回答

0

這些東西都不應該在控制器中。在模型的beforeDelete()中使用find('first')獲取記錄,並將文件名保存在模型屬性中。然後在afterDelete()刪除文件誰緩存在beforeDelete()緩存的文件。

相關問題