title: PHP Asynchronous Method Call In The Yii Framework
body: <h1>Question</h1>
  
  <p>I want to know if it is possible to asynchronously invoke a Yii controller method from one of its actions while the action renders a view, leaving the method to complete a long running operation. I would love to do something like the code below and I don't need to return a result from <code>my_long_running_func</code>.</p>
  
  <pre><code>public function actionCreate() {
      $model = new Vacancies;
      if (isset($_POST['Vacancies'])) {
          $model-&gt;setAttributes($_POST['Vacancies']);
          $model-&gt;save();
          //I wish :)
          call_user_func_async('my_long_running_func',$model);
      }
      $this-&gt;render('create', array( 'model' =&gt; $model));
  }
  </code></pre>
  
  <h2>Problem</h2>
  
  <p>I am trying to write a controller action in Yii that posts a vacancy and notifies interested subscribers of the post. The problem is that it takes a long time to execute the notification query.</p>
  
  <p>Now I am searching for a way to asynchronously run the query so the poster sees his response in as little time as possible while the query runs in the background in a way similar to C# delegates or events.</p>
  
  <p>The solutions I googled up performed <em>asynchronous request(s)</em> during the course of the controller action but all I want to do is to run a method of the controller asynchronously and the action had to <em>wait</em> till the <em>request(s)</em> were completed.</p>
  
  <h2>Attempted</h2>
  
  <p>I have tried the following methods but the query is still slow for my test data of about 1500 users.</p>
  
  <ul>
  <li><p>Yii ActiveRecord</p>
  
  <pre><code>if ($vacancy-&gt;save()) {                
      if($vacancy-&gt;is_active == 1) {
          $url = Yii::app()-&gt;createUrl('vacancies/view',array('id'=&gt;$model-&gt;id));
          $trainees = YumUser::getUsersByRole('Trainees');
          if($trainees!=null) {
              foreach($trainees as $trainee){
                  $message = new YumMessage;
                  $message-&gt;from_user_id = Yii::app()-&gt;user-&gt;id;
                  $message-&gt;title = 'Vacancy Notification: '.date('M j, Y');
                  $message-&gt;message = "A new vacancy has been posted at &lt;a href='{$url}'&gt;{$url}&lt;/a&gt;.";
                  $message-&gt;to_user_id = $trainee-&gt;id;
                  $message-&gt;save();                
              }
          }
      }    
  }
  </code></pre></li>
  <li><p>Yii Data Access Objects</p>
  
  <pre><code>if ($vacancy-&gt;save()) {        
      if($vacancy-&gt;is_active == 1) {
          $url = Yii::app()-&gt;createAbsoluteUrl('vacancies/view',array('id'=&gt;$model-&gt;id));
          $trainee_ids=Yii::app()-&gt;db-&gt;createCommand()-&gt;select('user_id')-&gt;from('trainee')-&gt;queryColumn();
          $fid=Yii::app()-&gt;user-&gt;id;
          $msg="A new vacancy has been posted at &lt;a href='{$url}'&gt;{$url}&lt;/a&gt;.";
          $ts = time();
          $tt = 'Vacancy Notification: '.date('M j, Y');
          if($trainee_ids!=null) {
              foreach($trainee_ids as $trainee_id){
                  Yii::app()-&gt;db-&gt;createCommand()
                    -&gt;insert('message',array('timestamp'=&gt;$ts,'from_user_id'=&gt;$fid,'to_user_id'=&gt;$tid,'title'=&gt;$tt,'message'=&gt;$msg));
              }
          }
      }
  }
  </code></pre></li>
  <li><p>Prepared Statements</p>
  
  <pre><code>if ($vacancy-&gt;save()) {                
      if($vacancy-&gt;is_active == 1) {
          $url = Yii::app()-&gt;createUrl('vacancies/view',array('id'=&gt;$model-&gt;id));                    
          $trainee_ids=Yii::app()-&gt;db-&gt;createCommand()-&gt;select('user_id')-&gt;from('trainee')-&gt;queryColumn();
          $fu=Yii::app()-&gt;user-&gt;id;
          $msg="A new vacancy has been posted at &lt;a href='{$url}'&gt;{$url}&lt;/a&gt;.";
          $ts = time();
          $tt = 'Vacancy Notification: '.date('M j, Y');
          $sql="INSERT INTO message (timestamp,from_user_id,title,message,to_user_id) VALUES (:ts,:fu,:tt,:msg,:tu)";
          if($trainee_ids!=null) {
              foreach($trainee_ids as $trainee_id){
  
                  $command=Yii::app()-&gt;db-&gt;createCommand($sql);
                  $command-&gt;bindParam(":ts",$ts,PDO::PARAM_INT);
                  $command-&gt;bindParam(":fu",$fu,PDO::PARAM_INT);
                  $command-&gt;bindParam(":tt",$tt,PDO::PARAM_STR);
                  $command-&gt;bindParam(":msg",$msg,PDO::PARAM_STR);
                  $command-&gt;bindParam(":tu",$trainee_id,PDO::PARAM_INT);
  
                  $command-&gt;execute();
  
              }
          }
      }
  }
  </code></pre></li>
  </ul>
  
  <h2>Research</h2>
  
  <p>I have also checked the following websites (I'm only allowed to post two links) but they either require the action to wait for the request to be completed or need curl (which I don't have access to on the deployment server) or need an external library. I was hoping for a native PHP implementation. </p>
  
  <ul>
  <li>PHP Simulated Multi-Threading</li>
  <li>Multithreading in php</li>
  <li><a href="https://stackoverflow.com/questions/124462/asynchronous-php-calls">Asynchronous PHP calls?</a></li>
  <li><a href="http://css.dzone.com/articles/asynchronous-processing-php" rel="nofollow noreferrer">Asynchronous processing in PHP</a></li>
  </ul>
  
  <h2>Edit</h2>
  
  <p>I was able to decrease response time considerably by rewriting my query in this way (moving the user loop to the database layer):</p>
  
  <pre><code>public function actionCreate() {
      $user=YumUser::model()-&gt;findByPk(Yii::app()-&gt;user-&gt;id);
      $model = new Vacancies;
      $model-&gt;corporate_id=$user-&gt;professional-&gt;institution-&gt;corporate-&gt;id;
      $model-&gt;date_posted=date('Y-m-d');
      $model-&gt;last_modified=date('Y-m-d H:i:s');
  
      if (isset($_POST['Vacancies'])) {
          $model-&gt;setAttributes($_POST['Vacancies']);
          if ($model-&gt;save()) {                
              if($model-&gt;is_active == 1) {
                  $url = Yii::app()-&gt;createAbsoluteUrl('vacancies/view',array('id'=&gt;$model-&gt;id));                    
                  $fu=Yii::app()-&gt;user-&gt;id;
                  $msg="A new vacancy has been posted at &lt;a href='{$url}'&gt;{$url}&lt;/a&gt;.";
                  $ts = time();
                  $tt = 'New Vacancy: '.$model-&gt;title;
                  $sql='INSERT INTO message (timestamp,from_user_id,title,message,to_user_id) SELECT :ts,:fu,:tt,:msg,t.user_id FROM trainee t';
                  Yii::app()-&gt;db-&gt;createCommand($sql)-&gt;execute(array(':ts'=&gt;$ts,':fu'=&gt;$fu,':tt'=&gt;$tt,':msg'=&gt;$msg));
              }                
              if (Yii::app()-&gt;getRequest()-&gt;getIsAjaxRequest())
                  Yii::app()-&gt;end();
              else
                  $this-&gt;redirect(array('view', 'id' =&gt; $model-&gt;id));
          }
      }
      $this-&gt;render('create', array( 'model' =&gt; $model));
  }
  </code></pre>
  
  <p>Notwithstanding, it would be nice if someone could post a way to call functions asynchronously.</p>