Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PHP Hooks – The Complete Beginner’s Guide

INTRODUCTION
THE UNOFFICIAL HOOK

Welcome to a tutorial on PHP hooks. You may have heard of hooks or already used them in WordPress, Drupal, Codeigniter, and several other platforms… Or maybe you know other programming languages and wonder how hooks work in PHP. Well, for a quick answer – Hooks actually don’t exist in PHP. 

Yep, for you beginner code ninjas who are confused, this simply means that PHP does not implement the use of hooks natively; Wordpress, Drupal, and whatever package that you use has their own version of a “simulated hook”. Just what is happening here? What are hooks? Why do we need hooks? Read on to find out!

I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
The Basics

Section B
Hooks In PHP

Extra
Download & More

Closing
What’s Next?

SECTION A
THE BASICS

Before we go into the code examples, let us start by answering the raw basic questions and help you to better understand what is going on – Just what the heck is a hook, what does it do, and why do we need them?

WHAT IS A HOOK?

In computer programming, the term hooking covers a range of techniques used to alter or augment the behaviour of an operating system, of applications, or of other software components by intercepting Function calls or messages or events passed between software components.

So says Wikipedia, and several other geeky websites offer a similar answer. Just what does this mean? Maybe a more practical example will illustrate hooks better. Let’s just say that we have a function that deals with user registration, where it will save the user particulars into the database.

That should be straightforward enough, and what we will usually do. But here comes the twist – What if we want to check the input before processing the save? What if we want to send an email after a successful save?

This is where we use hooks to intercept the input for checks right before the saving starts, and intercept right after the save to send out an email.

WHY USE HOOKS?

Isn’t this foolish and inefficient? Why do we need to go through so much roundabout troubles to use hooks? We could have just modified the save user function, permanently code the input checks and send email in. Yes, we can. But that will mean we are also modifying the core function this way.

What if save user is a common function used across many systems? For example, an international company has a centralized users database and uses the same save user function. It does not make sense to modify the core function, as countries have different address formats, telephone formats, or maybe some countries do more than just sending out an email after saving.

This is why we need hooks. To keep the core function untouched, as individual regions or separate systems can implement their own customizations. That is also true vice-versa with the many packages – WordPress, Drupal, CodeIgniter, etc… We want to keep our customizations, and not lose it in a package update as the core library files are being replaced with the new version.

HOOKS VS CALLBACK VS EVENTS

At this stage, some of you advanced code ninjas should be thinking that hooks are something like events and callbacks – Yes, they are close relatives, but not the same.

  • Events are fired when something happens, and we write blocks of code to deal with the situation.
  • A callback is a function that is passed into another function as a parameter.
  • Hooks are interceptors. They interrupt the normal process and we usually place them before the function starts, or just before the function ends.

SECTION B
HOOKS IN PHP

Sadly, hooks are not natively available in PHP, but that does not stop us from having our own “hook-like” implementations in PHP. I mean, WordPress, CodeIgniter, and Drupal all have their own hook implementations. Just how do we do it? Find out in this section.

P.S. Please read the official documentation of those packages on how to use their hooks. This section will only walk through how we can possibly emulate hooks in raw PHP.

HOOKS WITH FUNCTIONS

This is one of the more common ways to emulate hooks in PHP, by running functions if they exist. We shall reuse our above example on saving a user to the database, and here is the core library file that will do the saving.

1-lib-users.php
stmt = $this->pdo->prepare($sql);
      // $pass = $this->stmt->execute($input);
    }

    // AFTER HOOK
    if ($pass && function_exists("afterUserSave")) {
      $pass = afterUserSave($data);
    }

    // THE RESULT
    return $pass;
  }
}

Notice those two function_exists? Yep, we only need to define these functions and they will act as our hooks.

1-users.php
";
  print_r($user);
  echo "
"; // Do some checks here $pass = true; if (strlen($user['name'])"; // Send confirmation email to user // @mail($user['email'], "Welcome", "Your account has been created"); return true; } // DUMMY USER TO SAVE $user = [ "name" => "John Doe", "email" => "[email protected]", "tel" => "123456", "pass" => "VERYSECRET" ]; // PROCESS SAVE $pass = $userLib->saveUser($user); echo $pass ? "OK" : "ERROR!";

Problem is, we are going to need to define a lot of global functions this way. Even though we can use namespace to kind of organize it better, it is still potentially unhealthy to the memory usage with a ton of “hook functions” just floating around.

HOOKS INTO EXTERNAL SCRIPTS

This is an alternate version where we put the hook scripts into separate files instead. We start with the core library as usual, but take note that we look for an external script with file_exists instead of a function now.

2-lib-users.php
stmt = $this->pdo->prepare($sql);
      // $pass = $this->stmt->execute($input);
    }

    // AFTER HOOK
    if (file_exists("2-hook-saveuser-after.php")) {
      include "2-hook-saveuser-after.php";
    }

    // THE RESULT
    return $pass;
  }
}

Next, we have our hook scripts.

2-hook-saveuser-before.php
";
print_r($data);
echo "
"; // Do some checks here $pass = true; if (strlen($data['name'])
2-hook-saveuser-after.php
";
// Send confirmation email to user
// @mail($data['email'], "Welcome", "Your account has been created");

Finally, the process script.

2-users.php
 "John Doe",
  "email" => "[email protected]",
  "tel" => "123456",
  "pass" => "VERYSECRET"
];

// PROCESS SAVE
$pass = $userLib->saveUser($user);
echo $pass ? "OK" : "ERROR!";

This method is a lot cleaner than defining a ton of functions, but also, quite a bit slower since it has to hunt for external scripts.

HOOKS WITH CALLBACK

This final method is kind of unorthodox, where we pass callback functions into the core library and use them as hooks instead.

3-lib-users.php
stmt = $this->pdo->prepare($sql);
      // $pass = $this->stmt->execute($input);
    }

    // AFTER HOOK
    if ($after!=null) {
      $after($data);
    }

    // THE RESULT
    return $pass;
  }
}
3-users.php
 "John Doe",
  "email" => "[email protected]",
  "tel" => "123456",
  "pass" => "VERYSECRET"
];

// PROCESS SAVE
$pass = $userLib->saveUser($user, 
// Before hook
function ($data) {
  echo "BEFORE USER SAVE HOOK
"; print_r($data); echo "
"; // Do some checks here $pass = true; if (strlen($data['name'])"; // Send confirmation email to user // @mail($data['email'], "Welcome", "Your account has been created"); }); echo $pass ? "OK" : "ERROR!";

I know, some of the hater flamer trolls here are going to say “that is not how we are supposed to use callback functions”… But hey – It works.

WHICH IS THE BEST?

All of the above methods are possible solutions, and whichever works best for your project is the best method… But personally, I am leaning towards defining global functions – That is how most of the frameworks and packages work too.

EXTRA
DOWNLOAD & MORE

That’s all for the code, and here is the download link for all the above example code as promised.

SOURCE CODE DOWNLOAD

Click here to download the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
  

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand hooks, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post PHP Hooks – The Complete Beginner’s Guide appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

PHP Hooks – The Complete Beginner’s Guide

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×