如何在所有控制器函数中加载一个辅助函数,而不是每次都在所有函数中调用它

时间:2017-09-11 09:53:32

标签: php codeigniter

我想在所有控制器函数中添加这些辅助函数

// this is my helper file custom_helper.php

// $autoload['helper'] = array('url','form', 'custom_helper');

function notifications()
{
    $CI = get_instance();
    $CI->load->model('custom_model');
    $select = "id, name";
    $tableName = "users";
    $whereCondition = "created_at = CURDATE()";
    $result = $CI->custom_model
                     ->FetchWithSelect($select,$tableName,$whereCondition);       
    return $result;
}

4 个答案:

答案 0 :(得分:2)

在application / helper文件夹中创建帮助文件:xyz_helper.php

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

    function notifications() 
    {
        $CI = get_instance();
        $CI->load->model('custom_model');
        $select = "id, name";
        $tableName = "users";
        $whereCondition = "created_at = CURDATE()";
        $result = $CI->custom_model
                     ->FetchWithSelect($select,$tableName,$whereCondition);       
        return $result;
    }

然后打开application / config / autoload.php文件:添加此

$autoload['helper'] = array('url', 'file','form','xyz');

此外,您不需要将&#34; custom_helper&#34;在$ autoload [&#39; helper&#39;]中,只需添加&#34; custom&#34;和application / helper / custom_helper.php中的文件

答案 1 :(得分:1)

在/application/config/autoload.php中更改:

$autoload['helper'] = array();

$autoload['helper'] = array('html', 'url');

答案 2 :(得分:0)

您的控制器可能会扩展Codeigniter控制器类。所以,你想要的是另一个扩展它的类:

<?php

class Basecontroller extends CI_Controller
{
    public function notifications()
    {
        $CI = get_instance();
        $CI->load->model('custom_model');
        $select = "id, name";
        $tableName = "users";
        $whereCondition = "created_at = CURDATE()";
        $result = $CI->custom_model
                     ->FetchWithSelect($select,$tableName,$whereCondition);       
        return $result;
    }
}

然后在所有控制器中扩展该类!

<?php

class Home extends Basecontroller
{
    public function someActionOrOther()
    {
        $this->notifications(); // now works
    }
}

答案 3 :(得分:0)

通过在每个控制器的构造函数中调用辅助函数,我认为不需要在每个控制器函数中调用辅助函数