execute js function by php command line

2019-03-03 17:09发布

I am working in Codeigniter. I have a view, book.php, with a js file, frontend_book.js, running behind it containing a function to sync the calendar.

Snippet from frontend_book.js

googleSync: function() {
    provider_id= $('#select-provider').val();
    getUrl = GlobalVariables.baseUrl + 'google/sync/' + provider_id;
    jQuery.get(getUrl,provider_id, console.log('Google sync successful'),'json');
}

I would like to run this function independent of the view in a cron job using a php function in my google.php controller, that does something like this:

public function syncallproviders() {

    //get the array of providers:
    $this->load->model('providers_model');
    $providers = $this->providers_model->get_available_providers();

    //for each providers as provider run the js googleSync
    foreach ($providers['id'] as $provider) {

        //Run googleSync where #select-provider is $provider

    }
}

That I can then run in a cron job with

 php /mypath/index.php "google" syncallproviders

How do I integrate this?

This is my best guess at putting the two together:

<?php
    //get the array of providers:
    $this->load->model('providers_model');
    $providers = $this->providers_model->get_available_providers();

    //for each providers as provider run google sync
    foreach ($providers as $provider) { ?>  
    <script type="text/javascript">
        var getUrl=<?php echo $this->config->base_url().'/google/sync/'.$provider['id']; ?>,
        var provider_id =<?php echo $provider['id']; ?>,
        jQuery.get(getUrl,provider_id, console.log('Google sync successful'),'json'),
    </script>
<?php   }

Does this look right? Now how can I make this run from a command line? What can take the place of a browser if I run it from command line?

2条回答
祖国的老花朵
2楼-- · 2019-03-03 17:52

if, for what ever reason, you wanted to run this as a cron, and you wanted to maintain the application as it is now (mvc written in php) then you could use a headless browser (such as phantomjs) to hit the desired url from a bash script that is run as a cron. This is a bit convoluted - but it would do what you wanted. - there is even a php package if you wanted to keep it all via php - http://jonnnnyw.github.io/php-phantomjs/

查看更多
太酷不给撩
3楼-- · 2019-03-03 18:01

You can't make js run from the command line. It only runs in browsers and other environments set up to execute it. Everything you want to do you'll have to do in PHP or another language that runs on the command line.

查看更多
登录 后发表回答