2015-08-08 20 views
3

我想向服務器發送一個410在CakePHP中沒有發佈的舊URL的響應。如何發送一個410在cakephp中不見了

CakePHP提供了各種例外,如404,500等,但沒有什麼像410了。

有沒有什麼辦法可以讓我的服務器410去了迴應,如果有人打開一箇舊網址,不再存在的網站,但曾經是。

感謝,

回答

0

我做了以下內容來解決這一點。

我加入 「AppExceptionRenderer」 「水漲船高」 功能

public function gone($error) { 

     $this->controller->layout = 'nopageexists'; 

     $this->controller->set('title_for_layout', __('CriticalPast.com: Page not found')); 
     $this->controller->set('meta_description', ''); 
     $this->controller->set('meta_keywords', ''); 

     // This will execute 404 Error Page without redirection added by vinod... 
     $this->controller->response->statusCode(410); 
     $this->controller->render('/Errors/error404'); 
     $this->controller->response->send(); 
    } 

創建一個自定義類在app /庫/ myException.php

class GoneException extends CakeException { 

/** 
* Constructor 
* 
* @param string $message If no message is given 'Not Found' will be the message 
* @param integer $code Status code, defaults to 410 
    */ 
    /* 
    public function __construct($message = null, $code = 410) { 
     if (empty($message)) { 
      $message = 'Gone'; 
     } 
     parent::__construct($message, $code); 
    } 
    */ 
    protected $_messageTemplate = 'Test'; 
} 

在控制器添加下面,我想展示410不見了。

throw new GoneException('Gone', 410); 

這對我有效。請投我的答案,可以幫助其他用戶。

問候。

2

的首選方法是拋出異常。異常擴展HttpException。你也可以從這個類繼承並創建你自己的自定義異常。

https://github.com/cakephp/cakephp/blob/3.0.11/src/Network/Exception/BadRequestException.php

<?php 

use Cake\Network\Exception\HttpException; 

class GoneException extends HttpException 
{ 
    /** 
    * Constructor 
    * 
    * @param string $message If no message is given 'Gone' will be the message 
    * @param int $code Status code, defaults to 410 
    */ 
    public function __construct($message = null, $code = 410) 
    { 
     if (empty($message)) { 
      $message = 'Gone'; 
     } 
     parent::__construct($message, $code); 
    } 
} 
+0

爲您的幫助。我重寫了解決此問題的「AppExceptionRenderer」。請參閱我的答案中的詳細信息。 –