0

コントローラーのコンストラクターに配置する単純なコードがあります

$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");

ログアウトの安全のためにこのコードを使用します。私の質問は、コードをコントローラーごとにグローバルとして配置/宣言する方法はありますか? 各コントローラーのコンストラクターですべてをハードコーディングするのは難しいためです。

お手伝いありがとう。

4

4 に答える 4

1

私はすべての答えが好きですが、最良のアプローチはフックを使用することです。最初にこれをhooks.phpに追加します

 $hook['display_override'] = array(
    'class'    => 'RouteProcess',
    'function' => 'afterroute',
    'filename' => 'RouteProcess.php',
    'filepath' => 'hooks',
    'params'   => array()
 );

次に、hooks/ フォルダーに移動し、RoutesProcess.php を作成します。以下のファイルを作成します。

class RouteProcess{
function afterroute(){
    $this->CI =&get_instance();
     $this->CI->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
    $this->CI->output->set_header("Pragma: no-cache");
    echo $this->CI->output->get_output();
}
}

これの良いところは、オーバーライドできるコントローラーの __construct() を呼び出す必要がないことです。これは何があっても呼び出されます。

于 2015-05-15T10:18:38.657 に答える
1

コア ディレクトリを介してデフォルトの CI_Controller を拡張できます

application/core/MY_Controller.php: (MY_ 部分は config.php で定義されています)

class BaseController extends CI_Controller {

    public function __construct() {
      parent::__construct();
      $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
      $this->output->set_header("Pragma: no-cache");
    }
}

次に、コントローラーで次を使用します。

class ControllerXYZ extends BaseController {
    //your code
}

BaseController の機能を必要としないコントローラーがある場合は、basecontroller から拡張するのではなく、CI_Controller から拡張します。

class ControllerXYZ extends CI_Controller {
    //your code without the headers set
}

これには、各コントローラーが必要とするより多くのコードを重複排除するという利点もあります。たとえば、誰かがログインしているかどうかを確認するには、次のようにすることができます。

class BaseController extends CI_Controller {

      public function __construct() {
          parent::__construct();
          $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
          $this->output->set_header("Pragma: no-cache");

          if(!$this->session->userdata('loggedIn') === True) {
              redirect('/loginpage');
          }
      }
}

詳細については、 https://ellislab.com/codeigniter/user-guide/general/core_classes.htmlを参照してください。

于 2015-05-15T05:28:13.730 に答える