Pour ceux qui se demandaient de quoi je parlais, voici l'exemple de plugin WordPress qui démontre l'utilité de la création de fonctions dynamiques.
/* Plugin Name: Sample Action Hooks with Dynamic Functions */
// assuming this is an option retrieved from the database
$oActions = array( 'a' => array('interval' => 10, 'value' => 'hi'),
'b' => array('interval' => 30, 'value' => 'hello'),
'c' => array('interval' => 60, 'value' => 'bye')
);
add_action('init', LoadEvents);
function LoadEvents() {
global $oActions;
foreach($oActions as $strActionName => $array) {
eval( 'function ' . $strActionName . '() {
SampleEvents(\'' . $strActionName . '\');
}'
);
add_action('sampletask_' . md5($strActionName), $strActionName);
if (!wp_next_scheduled( 'sampletask_' . md5($strActionName)))
wp_schedule_single_event(time() + $oActions[$strActionName]['interval'], 'sampletask_' . md5($strActionName));
}
}
function SampleEvents($strActionName) {
global $oActions;
// just log for a demo
$file = __DIR__ . '/log.html';
$current = date('l jS \of F Y h:i:s A') . ': ' . $strActionName . ', ' . $oActions[$strActionName]['value'] . '<br />' . PHP_EOL;
file_put_contents($file, $current, FILE_APPEND);
wp_schedule_single_event(time() + $oActions[$strActionName]['interval'], 'sampletask_' . md5($strActionName));
}
Et la même fonctionnalité pourrait être obtenue avec __call()
.
/* Plugin Name: Sample Action Hooks */
add_action('init', create_function( '', '$oSampleEvents = new SampleEvents;' ));
class SampleEvents {
public $oActions = array( 'a' => array('interval' => 10, 'value' => 'hi'),
'b' => array('interval' => 30, 'value' => 'hello'),
'c' => array('interval' => 60, 'value' => 'bye')
);
function __construct() {
foreach($this->oActions as $strActionName => $arrAction) {
add_action('sampletask_' . md5($strActionName), array(&$this, $strActionName));
if (!wp_next_scheduled( 'sampletask_' . md5($strActionName)))
wp_schedule_single_event(time() + $this->oActions[$strActionName]['interval'], 'sampletask_' . md5($strActionName));
}
}
function __call($strMethodName, $arguments) {
// just log for a demo
$file = __DIR__ . '/log.html';
$current = date('l jS \of F Y h:i:s A') . ': ' . $strMethodName . ', ' . $this->oActions[$strMethodName]['value'] . '<br />' . PHP_EOL;
file_put_contents($file, $current, FILE_APPEND);
wp_schedule_single_event(time() + $this->oActions[$strMethodName]['interval'], 'sampletask_' . md5($strMethodName));
}
}