How to destroy Codeigniter library instance

百般思念 提交于 2019-12-24 02:44:10

问题


I would like to know if there is any way I can destroy a Codeigniter library instance.

What I want to do is something like this:

$this->load->library('my_library');
/**
    Code goes here
**/
$this->my_library->destoy_instance();

The reason I need to do this is because I need to liberate RAM memory while executing a large scripts.

Any help will be greatly appresiated.


回答1:


You can do simply like that by using unset or setting null.

unset($this->my_library);

OR

$this->my_library = null;

This answer is also worth reading for you to know detail about these two ways.

Edit

There is no built-in method to destroy loaded library object. But you can do it by extending Loader class. And then load and unload library from that class. Here is my sample code ..

application/libraries/custom_loader.php

class Custom_loader extends CI_Loader {
    public function __construct() {
        parent::__construct();
    }

    public function unload_library($name) {
        if (count($this->_ci_classes)) {
            foreach ($this->_ci_classes as $key => $value) {
                if ($key == $name) {
                    unset($this->_ci_classes[$key]);
                }
            }
        }

        if (count($this->_ci_loaded_files)) {
            foreach ($this->_ci_loaded_files as $key => $value)
            {
                $segments = explode("/", $value);
                if (strtolower($segments[sizeof($segments) - 1]) == $name.".php") {
                    unset($this->_ci_loaded_files[$key]);
                }
            }
        }

        $CI =& get_instance();
        $name = ($name != "user_agent") ? $name : "agent";
        unset($CI->$name);
    }
}

In your controller ..

$this->load->library('custom_loader');
// To load library
$this->custom_loader->library('user_agent');
$this->custom_loader->library('email');

// To unload library
$this->custom_loader->unload_library('user_agent');
$this->custom_loader->unload_library('email');

Hope it will be useful.




回答2:


Ok, I found a solution to this if you need to re-create the same object within the same controller. The trick it to pass in the third property which is a custom name you can assign the object.

$this->load->library('my_library', $my_parameters, 'my_library_custom_name');

If you just want to unset the object PHP will take care of that. You can confirm using a destructor on your class.

public function __destruct() {

    // do something to show you when the object has been destructed

}


来源:https://stackoverflow.com/questions/29062291/how-to-destroy-codeigniter-library-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!