Codeigniter:在控制器中全局存储变量-如何在CI上做到这一点?它的效率更高吗


Codeigniter: Storing variables globally in a controller - How do I do this on CI? And is it more efficient?

我在CodeIgniter控制器中有这个函数,它获取变量并设置发送电子邮件的配置:

// Sends to email the results 
public function send_mail($id, $name, $msg, $send){
    if ($send) {
        $ci = get_instance();
        $config['protocol']  = "smtp";
        $config['smtp_host'] = "ssl://smtp.gmail.com";
        $config['smtp_port'] = "465";
        $config['smtp_user'] = "myname@potato.pro"; 
        $config['smtp_pass'] = "ilovepotatos";
        $config['charset']   = "utf-8";
        $config['mailtype']  = "html";
        $config['newline']   = "'r'n";
        $config['crlf']      = "'r'n";
        $config['validate']  = FALSE;
        $ci->load->library('email');
        $ci->email->initialize($config);
        $ci->email->from('myname@potato.pro', 'Keyword Alerting System (KAS)');
        $list = array('myname.fname@gmail.com', 'sagi@potato.pro');
        $ci->email->to($list);
        $this->email->reply_to('no-reply@potato.pro', "KAS Alert $kas_keyword");
        $ci->email->subject('KAS Alert!');
        $ci->email->message("text");
        $ci->email->send();
    } 
}

因此,每当调用这个函数时,它都会设置这些配置。我想让它更有效率。

有没有更有效的方法来为所有控制器存储这样的东西?

我可以把它添加到__construct函数中吗?$config变量对控制器来说是全局的吗?

我可以包括吗

    $ci->load->library('email');
    $ci->email->initialize($config);

也是吗?

这会有效率吗?还是只在调用函数时才调用它们更好?

底线:

在控制器中全局存储变量-如何在CI上执行此操作?它的效率更高吗?更推荐在哪些情况下全局存储变量。

尝试创建一个父控制器。

class MY_Controller extends CI_Controller {
var $url;
function __construct() {
    parent::__construct();
    // *********************** Load Library ****************************
    $this->load->library('session');
    //**************** set value to $url
    $this->url = "https://192.168.10.46/soap/soap.php?wsdl";
   }
}

因此,您将从MY_controller扩展的任何控制器中获得$url值,比如这个

$this->url;

也可以看看这里。http://blog.aztora.com/codeigniter-storing-variables-globally-in-a-controller-how-do-i-do-this-on-ci/