0

In my CodeIgniter 2 controller I call a model method which returns a ReactPHP promise, and I want to load a CodeIgniter view in the function called by that promise's ->then() method. How can I do this? What happens instead is the controller method returns nothing, so I get a blank page in the browser.

Here is a simplified example illustrating what I'm trying to do:

class My_class extends My_Controller {

    function my_method() {

        $this->my_model->returns_a_promise()->then(function ($data) {

            // How can I pass the promise's resolved value to the template here?
            // It seems this never gets called, because my_method() returns 
            // before we get here. :(
            $this->load->view('my_view', $data);

        });

    }

}

Is there any way to tell the controller method not to send output to the browser until after the promise has resolved?

timblack1
  • 137
  • 7

3 Answers3

1

I'm not sure what are you trying to do but if you want to stop view from outputting and return it as a string then output it with echo yourself you can do this:

$view = this->load->view('my_view', $data, TRUE);

Now you have the view as a var string you can use it to do what you are trying to do.

Sherif Salah
  • 2,085
  • 2
  • 9
  • 21
0

It turns out the code in my original question does work. So the question is the answer. But the reason it wasn't working for me was that returns_a_promise() was not returning a resolved promise, so ->then() was not called and the view was not rendered. In order to make it return a resolved promise, I had to call $deferred->resolve(); in the code that returned the promise.

The upshot of this is that this code example demonstrates it is possible to run asynchronous PHP (via ReactPHP in this case) in CodeIgniter controller methods. My particular use case is to run many database queries concurrently in the CodeIgniter model.

timblack1
  • 137
  • 7
0

try this:

 function  my_method() {
        $data = array();
       $data['promise'] =$this->my_model->returns_a_promise();
         $data['view'] = 'my_view';
        $this->load->view('my_view', $data);
    }
PHP Geek
  • 3,949
  • 1
  • 16
  • 32