我试图通过单独的AJAX调用在使用Codeigniter编写的同一控制器中调用不同的方法,并在其中一个调用中创建第三个库的对象,然后在第二个方法中访问相同的对象(也自动加载SESSION库),同时进行第二个AJAX调用:
Javascript有两个独立的AJAX调用:
$.post('http://mysite.com/UserController/controllerA',{Param1:x,Param2:y});
$.post('http://mysite.com/UserController/controllerB');
控制器看起来像:
require_once 'FILEPATH/Thirdlibrary.php';
class UserController extends CI_Controller {
protected $service;
public controllerA{
$varA = $this->input->post('Param1');
$varB = $this->input->post('Param2');
$this->service = new ThirdLibray($varA,$varB);
$this->service->startCall();//Thirdlibrary has method startCall() and stopCall
}
public controllerB{
//I want to refer to the same object $this->service here
$this->service->stopCall();
}
现在我知道PHP每次加载/访问时都会重新初始化对象,我该怎么做呢?如何克服这种错误:
Call to a member function stopCall() on a non-object
(努力搜索编码后在此查询)
将对象存储到会话中并使用。
require_once 'FILEPATH/Thirdlibrary.php';
class UserController extends CI_Controller {
protected $service;
public controllerA{
$varA = $this->input->post('Param1');
$varB = $this->input->post('Param2');
if($this->session->userdata('lib_service'))
{
$this->service =$this->session->userdata('lib_service');
}
else
{
$this->service = new ThirdLibray($varA,$varB);
}
$this->service->startCall();//Thirdlibrary has method startCall() and stopCall
$this->session->set_userdata('lib_service',$this->service); // Why i am saving the object here?, startCall may update some object properties, so that-also will be saved. Otherwise you can have this line in the else part above, after object creation.
}
public controllerB{
//I want to refer to the same object $this->service here
if($this->session->userdata('lib_service'))
{
$this->service =$this->session->userdata('lib_service');
$this->service->stopCall();
// Here after stop if you don't want the object, you can clear from session.
}
}
你可以尝试使用php的Singleton模式。这是实现它的基本代码为您的情况,但我不确定它会为您工作。让我们尝试:
-
首先为第三方库创建一个包装类:ThirdlibraryWrapped.php,你可以看到更多关于单例的PHP单例类的最佳实践
类ThirdLibraryWrapped {public ThirdLibray thirdLibrary; public static function Instance($param1=null,$param2 = null) { static $inst = null; if ($inst === null) { $inst = new ThirdlibraryWrapped($param1,$param2); } return $inst; } private function __construct($param1,$param2) { if($param1!=null && $param2 != null) thirdLibrary = new ThirdLibrary($param1,$param2); else //default constructor of thirdLibrary thirdLibrary = new ThirdLibrary(); }}
-
为您的控制器代码:
require_once 'FILEPATH/ThirdlibraryWrapped.php'; class UserController extends CI_Controller { protected $service; public controllerA{ $varA = $this->input->post('Param1'); $varB = $this->input->post('Param2'); $this->service = ThirdlibraryWrapped::Instance($varA,$varB); $this->service->thirdLibrary->startCall();//Thirdlibrary has method startCall() and stopCall } public controllerB{ //I want to refer to the same object $this->service here $this->service = ThirdlibraryWrapped::Instance(); $this->service->thirdLibrary->stopCall(); }}