PHP

HOW TO CREATE HOOKS IN PHP

Hooks are mechanics to alter or change a process.

PHP does not suport hooks natively.

We can only simulate hooks in PHP.

WHAT ARE HOOKS?

01

function save ($name, $email) {   SAVE USER   $pdo = new PDO(...);   $stmt = $pdo->prepare("INSERT INTO    `usr` (`name`, `email`) VALUES (?,?)");   $ok = $stmt->execute([$name, $email]);

HOOKS USING FUNCTIONS (A)

02

  HOOK   if ($ok && function_exists("after"))   { $ok = after($name, $email); }      RESULT    return $ok;  }

AFTER SAVE - SEND EMAIL function after ($name, $email) {   return mail($email, "HI!", "Message"); }

GO! echo save ("Jon", "jon@doe.com")   ? "OK" : "Error" ;

HOOKS USING FUNCTIONS (B)

03

function save ($name, $email, $hook) {   SAVE USER   $pdo = new PDO(...);   $stmt = $pdo->prepare("INSERT INTO    `usr` (`name`, `email`) VALUES (?,?)");   $ok = $stmt->execute([$name, $email]);

HOOKS USING CALLBACK (A)

04

  HOOK   if (is_callable($hook))    { $ok = $hook($name, $email); }      RESULT    return $ok;  }

HOOKS USING CALLBACK (B)

05

AFTER SAVE - SEND EMAIL function after ($name, $email) {   return mail($email, "HI!", "Message"); }

GO! echo save ("Jon", "jon@doe.com", "after") ? "OK" : "Error" ;

function save ($name, $email, $after) {   SAVE USER   $pdo = new PDO(...);   $stmt = $pdo->prepare("INSERT INTO   `usr` (`name`, `email`) VALUES (?,?)");   $ok = $stmt->execute([$name, $email]);

EXTERNAL SCRIPT HOOK (A)

06

  HOOK   if ($ok && file_exists($after))   { include $after; }      RESULT    return $OK;  }

AFTER.PHP $OK = mail($email, "HI!", "Message");

EXTERNAL SCRIPT HOOK (B)

07

GO! echo save ("Jon", "jon@doe.com", "after.php") ? "OK" : "Error" ;