我想创建一个钩子来检查我的项目是否处于维护模式
一切都很好
但数据库调用不起作用
我尝试
hooks.php
$hook['pre_controller'][] = array(
'class' => 'maintenance',
'function' => 'maintenance_check',
'filename' => 'maintenance.php',
'filepath' => 'hooks'
);
maintenance.php
public function maintenance_check(){
$this->load->database();
$result = $this->db->query('SELECT * FROM maintenance');
if($result[0]->mode === TRUE){
echo 'maintenance';
}
}
error => Undefined property: Maintenance::$load
您的问题是$this->负载在您的类中不存在
一个答案是使用'post_controller_constructor'
。这允许您扩展CI_Controller并访问所有的好东西。
$hook['post_controller_constructor'] = array(
'class' => 'Maintenance',
'function' => 'maintenance_check',
'filename' => 'Maintenance.php',
'filepath' => 'hooks'
);
你的维护类看起来像(我在里面有一些调试代码,看看发生了什么。(
<?php
class Maintenance extends CI_Controller {
public function maintenance_check() {
$this->load->database();
$result = $this->db->query('SELECT * FROM maintenance');
$mode = $result->row_array();
var_dump($mode['mode']);
if ($mode['mode'] == TRUE) {
echo 'maintenance';
}
}
}
不太确定维护表的架构。听起来更适合作为选项表中的条目id,name,value。
所以也许像
public function maintenance_check() {
$this->load->database();
$result = $this->db->query("SELECT value FROM options WHERE name='maintenance'");
$row = $result->row_array();
if ($row['value'] == TRUE) {
echo 'maintenance';
}
}
hooks.php
$hook['post_controller_constructor'] = array(
'class' => 'Maintenance',
'function' => 'maintenance_check',
'filename' => 'Maintenance.php',
'filepath' => 'hooks'
);
Maintenance.php
public function maintenance_check(){
$this->CI = &get_instance();
$result = $this->CI->db->query('SELECT * FROM maintenance');
if($result[0]->mode === TRUE){
echo 'maintenance';
}
}