【问题标题】:CodeIgniter accessing models from helperCodeIgniter 从 helper 访问模型
【发布时间】:2016-03-18 12:33:17
【问题描述】:

我正在为电子邮件功能编写 CodeIgniter 帮助程序,目前在我正在编写的每个函数中都需要:

$CI = &get_instance();
$CI
->email
//etc

这不是什么大问题,但我想知道是否有办法为所有函数加载一次 CI 实例?类似于构造方法的东西?

【问题讨论】:

  • 不确定您是否看过我的回答,但我已将其更新为更安全
  • 助手或者只是一堆函数,而不是一个类。你应该为此编写一个库,而不是一个助手。

标签: codeigniter


【解决方案1】:

如果您完全决定在帮助程序中定义您的函数而不是 extending CodeIgniter's email library,那么您可以这样做:

email_helper.php

<?php
// Assuming $CI has not been set before this point
$CI = &get_instance();

function some_email_function()
{
    $GLOBALS['CI']->email;
}

unset($CI);

【讨论】:

    【解决方案2】:

    您实际上可以这样做。

    这是一个例子

    <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class Example {
        public function __construct()
        {
            $this->CI =& get_instance();
        }
        public function functionExample(){
    
            $this->CI->load->module('fullpage');
            if($this->CI->fullpage->my_function() ){
               echo 'It works!'; 
            }
        }
    }
    

    【讨论】:

    • 根据 CI 的文档,Helper 不是类:“每个 helper 文件只是特定类别中的函数的集合......与 CodeIgniter 中的大多数其他系统不同,Helper 不是写在一个对象中定向格式。” ellislab.com/codeigniter/user-guide/general/helpers.html
    • 完全同意,但你总是可以创建一个库
    猜你喜欢
    • 1970-01-01
    • 2018-04-21
    • 2012-10-14
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多