CodeIgniter post_controller_constructor Hook 运行两次?

S. *_* S. 2 php hook codeigniter

我在 application\config\hooks.php 中有这个代码

$hook['post_controller_constructor'] = array(
'class' => 'maintenance',
'function' => 'maintenance',
'filename' => 'maintenance.php',
'filepath' => 'hooks',
'params' => array()
);
Run Code Online (Sandbox Code Playgroud)

和 application\hooks\maintenance.php 中的这段代码

class maintenance
{
   var $CI;    
   public function maintenance()
   {
    echo "Test";
   }
}
Run Code Online (Sandbox Code Playgroud)

和 application\config\config_maintenance.php 中的这段代码

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$config['maintenance'] = true;
Run Code Online (Sandbox Code Playgroud)

这是我的控制器的样子:

<?php
 class Home extends CI_Controller {
function __construct()
{
    parent::__construct();
    $this->load->model(array('home_model'));

}

function index()
{
    $this->load->view('home');
}
}
Run Code Online (Sandbox Code Playgroud)

当代码运行时,如果我不添加“exit;”,“Test”会在页面上回显两次。在 echo 语句之后。这是否意味着“post_controller_constructor”被调用了两次?

我想知道这是为什么,因为根据 CI 文档

post_controller_constructor: 在控制器实例化后立即调用,但在任何方法调用发生之前。

Pat*_*ser 5

好的,问题在于您的维护类和钩子定义。你调用钩子maintenance和函数maintenance。如果您以与类相同的方式命名方法,则此方法就是类构造函数。继续并重命名您的方法:

钩子.php

$hook['post_controller_constructor'] = array(
    'class' => 'maintenance',
    'function' => 'differentName',
    'filename' => 'maintenance.php',
    'filepath' => 'hooks',
    'params' => array()
);
Run Code Online (Sandbox Code Playgroud)

维护.php

class maintenance
{
   var $CI;    
   public function differentName()
   {
      echo "Test";
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 这里的问题是,您将方法称为“维护”,即类构造函数。类构造函数在类实例化时自动调用。然后 CodeIgniter 调用方法`maintenance` 无视它是类构造函数的事实。所以请记住,如果您将 Method 命名为与类相同的名称,那么此方法就是类构造函数。最好使用 `__construct()` 作为类构造函数 (2认同)