我应该在 CodeIgniter 中的什么位置定义自定义函数,以及如何在每个页面中使用它


Where should I define a custom function in CodeIgniter and how can I use it in every page?

我是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;
    }
}

首先创建公共模型然后将此函数放在其上并加载此模型

$autoload['model'] = array('mdl_common'); 

在配置中自动加载文件

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

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

您可以在您想要的每个页面中使用 尝试一下会有所帮助 .

这是合适的解决方案

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

现在在下面写代码.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();
            }
        }

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