PHP Asynchronous Method Call In The Yii Framework

后端 未结 3 1163
情深已故
情深已故 2021-02-05 22:57

Question

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

相关标签:
3条回答
  • 2021-02-05 23:27

    Here's an entirely different type of suggestion. What about registering for the onEndRequest event that is fired by CWebApplication's end() function?

    public function end($status=0, $exit=true)
    {
        if($this->hasEventHandler('onEndRequest'))
            $this->onEndRequest(new CEvent($this));
        if($exit)
            exit($status);
    }
    

    You'd need to register for the event and figure out how to pass your model in somehow, but the code would properly run after all the data has been flushed to the browser ...

    0 讨论(0)
  • 2021-02-05 23:41

    I would try this, though I'm not 100% that Yii will work properly, but its relatively simple and worth a go:

    public function actionCreate() {
        $model = new Vacancies;
        if (isset($_POST['Vacancies'])) {
            $model->setAttributes($_POST['Vacancies']);
            $model->save();
            //I wish :)
        }
    
        HttpResponse::setContentType('text/html');
        HttpResponse::setData($this->render('create', array( 'model' => $model), true);
        HttpResponse::send();
    
        flush(); // writes the response out to the client
    
        if (isset($_POST['Vacancies'])) {
            call_user_func_async('my_long_running_func',$model);
        }
    }
    
    0 讨论(0)
  • 2021-02-05 23:47

    Typically, the solution for these kind of problems would be to integrate a message-bus in your system. You could consider a product like Beanstalkd. This requires installing software on your server. I suppose this suggestion would be called "using an external library".

    If you can access the deployment server and you can add cronjob (or maybe a sysadmin can) you could consider a cronjob that does a php-cli call to a script that reads jobs from a job queue in your database which is filled by the controller method.

    If you cannot install software on the server you're running, you could consider using a SAAS solution like Iron.io to host the bus functionality for you. Iron.io is using what is called a push queue. With a push queue the message bus actively performs a request (push) to the registered listeners with the message content. This might work since it doesn't require you to do a curl request.

    If none of the above is possible, your hands are tied. Another post which is quite relevant on the subject: Scalable, Delayed PHP Processing

    0 讨论(0)
提交回复
热议问题