我应该在哪里定义CodeIgniter中的自定义函数,如何在每个页面中使用它?

时间:2016-03-15 09:50:01

标签: php codeigniter model-view-controller

我是CodeIgniter的新手。我想使用以下功能,需要在每个页面中运行。我在视图的顶部标题中调用该函数。即使在下面的内容中加载了不同的子视图,导航栏也应加载此功能,以便在每次运行时计算通知和消息。

function count_records_in_table($table, $where) 
{
    $this->db->select('count(id) as rows');
    $this->db->from($table);
    $this->db->where($where);
    $query = $this->db->get();
    foreach($query->result() as $r)
    {
       return $r->rows;
    }
}

2 个答案:

答案 0 :(得分:2)

这是合适的解决方案

 First create  one file say common.php in  application/libraries/common.php

现在在common.php文件中写下以下代码

        class Common extends CI_Controller 
        {
              public function customFailMessage($msg)
              {
                 $xml = new SimpleXMLElement('<Response/>');
                 $xml->addChild('status','success');
                 $xml->addChild('msg',"my message");
                 print ($xml->asXML());
                 die;
               }
        } 

现在从你的任何一个控制器中调用你的功能

        class Ws_plan extends CI_Controller 
        {
            public function __construct() 
           {
                parent::__construct();
                $this->load->library('common');
           }
           public function test()
            {
                        $this->common->customFailMessage();
            }
        }

希望您知道如何在所有控制器中使用通用功能

答案 1 :(得分:1)

首先创建通用模型 然后将此函数放在其上并在

中加载此模型
$autoload['model'] = array('mdl_common'); 

配置中的自动加载文件

最后,您可以通过调用这样的模型来使用您的函数

$this->mdl_common->count_records_in_table("table_name","where");

你可以在你想要的每个页面中使用它会有所帮助。