I'm trying to create a PrestaShop module which fires off a POST request using a hook.
The hook gets called like so:
if(is_callable(array($moduleInstance, 'hook'.$hook_name)) {
$moduleInstance->{'hook'.$hook_name}($hook_args);
}
Meaning to catch the hook event I need to have the method readily available in the class. So say I wanted to call a hook called myCustomEvent
, I'd need the following:
class myModule extends Module {
public function hookmyCustomEvent($params) {
}
}
However, what I'm wanting to do is store a list of hook events in a database and fire them when the hook is called. But to do that I need a method defined in the class. What I'd like to be able to do is have a sort of "magic"/wildcard method that would catch them all starting with hook
.
Is this possible?
Edit:
The methods don't exist, since I essentially want them to be dynamically called, executing another method.
Real code for examples:
public function hookactionValidateOrder($params) {
$this->fireWebhook('actionValidateOrder', $params);
}
public function hookactionOrderStatusUpdate($params) {
$this->fireWebhook('actionOrderStatusUpdate', $params);
}
public function hookactionUpdateQuantity($params) {
$this->fireWebhook('actionUpdateQuantity', $params);
}
private function fireWebhook($event, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, Configuration::get('HOOK_URL'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'event' => $event,
'data' => $data
]));
curl_exec($ch);
curl_close($ch);
}
public function __call($methodName, array $params) {
if (substr($methodName, 0, 4) === 'hook') {
// this matches something starting with "hook" so pull your instructions from the db here
}
}
Something like that would match a method without the need to explicitly define it as a class method, which I think was your intent?
To perform a method call on a dynamic definition use call_user_func or call_user_func_array
call_user_func( array($moduleInstance, 'hook'.$hook_name) , $hook_args );
As for your request to execute all methods starting with hook
i'd suggest the following:
class MyModule
{
/* ... */
public function executeHooks()
{
$methods = get_class_methods($this);
foreach ($methods as $method) {
if (substr($method, 0, 4) == 'hook') {
// Method is a hook
call_user_func( array($this, $method) );
}
}
}
/* ... */
}