4

Is it possible to implement event driven program in PHP?

Something like javascript.

As an example, try to open a socket(open_socket) and execute some other command(do_something_else) instead of waiting for the success response of socket request. After getting the success response execute callback_execute.

//--------------------------------------------------------------------
public function open_socket(){
$this->socketResource = fsockopen($this->nodeIp,$this->portNumber);
}

public function callback_execute(){
fputs($this->socketResource,$command);
}

public function do_something_else{ xxxxx }
//--------------------------------------------------------------------

Non_blocking_function($obj->open_socket(),$obj->callback_execute());
$obj->do_something_else(); 
P K
  • 9,972
  • 12
  • 53
  • 99
  • 1
    "implement code driven program," did you read your own writing? – Matt Ball Jan 16 '12 at 20:17
  • possible duplicate of [Event-Driven PHP Framework?](http://stackoverflow.com/questions/8856530/event-driven-php-framework) see also http://stackoverflow.com/questions/6846118/event-driven-architecture-and-hooks-in-php – Matt Ball Jan 16 '12 at 20:17
  • 2
    Because PHP can't be multithreaded, I'm going to go out on a limb and say "No". It is possible to mimic this with a variety of horrible process forking solutions, but a better solution if you want to do this sort of thing is to use something that can be multithreaded or more closely mimic it, like Java or Node.js. – DaveRandom Jan 16 '12 at 20:18
  • @MДΓΓ БДLL - i saw that question but answers doesn't give any hint. – P K Jan 16 '12 at 20:18

1 Answers1

3

There is only a single thread in PHP. Therefore doing something useful whilst waiting for some event is not possible in PHP.

Some workarounds are available but probably not very reliable – especially not when you plan to write portable code. I would assume the workarounds are risky since the language does not have a concept of concurrency. It's therefore probably best to write multi-threaded code in another language (Java, Scala, …) and use PHP just for displaying the prepared results (if using PHP at all for such problems).

Augustus Kling
  • 3,303
  • 1
  • 22
  • 25