我現在有一個依賴注入模塊,讓我來創建對象的工廠內一個全局對象:如何接入的方法封閉
class DiModule
{
private $Callbacks;
public function set(
$foo,
$bar
) {
$this->Callbacks[$foo] = $bar;
}
public function get(
$foo
) {
return $this->Callbacks[$foo];
}
}
然後我有一個事件對象存儲的方法關閉和會觸發事件。
class Event
{
private $Sesh;
private $Method;
public function set(
$sesh = array(),
$method
) {
$this->Sesh = $sesh;
$this->Method = $method;
}
public function get(
) {
return [$this->Sesh,$this->Method];
}
}
然後我有一個偵聽器對象,它搜索會話集並觸發與該對象關聯的事件。
class Listener
{
private $Sesh;
public function setSesh(
$foo
) {
$this->Sesh = $foo;
}
private $Event;
public function set(
$foo,
Event $event
) {
$this->Event[$foo] = $event;
}
public function dispatch(
$foo
) {
$state = true;
if(isset($this->Event[$foo]))
{
foreach($this->Event[$foo]->get()[0] as $sesh)
{
if(!isset($this->Sesh[$sesh]) || empty($this->Sesh[$sesh]))
{
$state = false;
}
}
}
return ($state) ? [true, $this->Event[$foo]->get()[1]()] : [false, "Event was not triggered."];
}
}
這是正在執行
$di = new DiModule();
$di->set('L', new Listener());
$di->set('E', new Event());
$di->get('E')->set(['misc'], function() { global $di; return $di; });
$di->get('L')->setSesh(array('misc' => 'active')); // not actual sessions yet
$di->get('L')->set('example', $di->get('E'));
var_dump($di->get('L')->dispatch('example'));
這樣的一個例子的問題是,當我嘗試訪問我的全球$di
封閉裏面,我用Google搜索這個無數次,但無法找到一個解決方案。
在你的示例代碼中可能只是一個錯誤,但對我來說,它看起來像你的'DiModule''''和'get'方法混淆了。 'set'返回對象,'get'設置它。 – Andy