我有一个个人项目,该项目使用Symfony的Process组件(利用php的proc_open())运行带有多个PHP子进程的主进程。我还有一个Event类,其中listens
的事件为triggered
:
Event.php
class Event
{
private $events = [];
public function listen($name, $callback)
{
$this->events[$name][] = $callback;
}
public function trigger($name, $argument = null)
{
foreach ($this->events[$name] as $event => $callback)
{
if($argument && is_array($argument)) {
call_user_func_array($callback, $argument);
} elseif ($argument && !is_array($argument)) {
call_user_func($callback, $argument);
} else {
call_user_func($callback);
}
}
}
}
Parent.php
class Parent
{
private $process;
public $event;
protected function __construct()
{
$this->event = new Event();
$this->event->listen('customEvent', function(){
echo 'A custom event was fired!'.PHP_EOL;
});
$this->process = new Process('php Child.php');
}
protected function run()
{
$this->process->start();
while($this->process->isRunning()) {}
}
}
Child.php
class Child
{
public $event;
protected function __construct()
{
$this->event = new Event();
}
protected function run()
{
while(true) {
if($condition == true) {
$this->event->trigger('customEvent');
}
}
}
}
如果从父进程中调用$this->event->trigger('customEvent');
方法,则会得到所需的结果(A custom event was fired!\n
)。如何在子进程中调用trigger()
方法,以便它可以触发在主进程中定义的回调函数(使用$this->event->listen()
)?该应用程序将在Linux系统上运行。所有名称空间均已正确配置,没有粘贴它们以获得更好的可读性。