Automatic method execution

Asked

Viewed 415 times

1

I have an x class that needs to run a y method once a day. However, how to do this in Object-Oriented PHP?

P.S.: In structured PHP, it used crontab or fcron to program that a given URL was executed at a certain time. In that script, I put the necessary modifications.

3 answers

2

Just point at this scheduled URL a file with the method call of that class

File Class:

<?php

// path/minhaClasse.php

class minhaClasse{
    public function meuMetodo($parametro){
        // Faz alguma coisa
    }

    public static function meuMetodoEstatico($parametro){
        // Roda o mesmo método, porém de forma estática
        return $this->meuMetodo($parametro);
    }
}

File with class call

<?php
require "path/minhaClasse.php";

$classe = new minhaClasse();
$classe->meuMetodo('parametro');

Or you can use a static call:

<?php
require "path/minhaClasse.php";

\minhaClasse::meuMetodoEstatico('parametro');

1

You will still have to run cron to schedule the php call, since php depends on a request to be interpreted.

You can write a class in PHP and use the methods class_exists to check whether the class x exists, if it exists you create an instance of it and use the method, method_exists to check whether the method y exists. If it exists, you execute the method.

You can use php as a script to call it in terminal via cli, just inform that the text interpreter to be used is php, adding an instruction similar to the instruction after the beginning of the file, (I speak similar, because it should have the path of your php interpreter, if you do not know where to find can type in the console whereis php, which will be displayed).

#!/usr/local/bin/php

I’m assuming you’re using linux.

0

An unusual way to solve your problem without using the CRON would be with a script that runs an infinite loop with the following content (or something like):

<?php

while(true){
    checkRemoteSite();
    updateYourDB();
    sleep(6000);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.