Senior PHP Engineer | Former E-commerce Website Manager | Full Stack Web Developer

PHP Hook System – Code Snippet

While working with PHP I’ve always used functions & classes, but when I took a look through the MyBB code, I noticed some form of hooks being used in order to generate certain parts of code.

Why use a ‘hook’ system?

Using Hooks allows you to easily make additions to code from any point that is before the hook is eventually ran. It lets you create a plugin system that would add additional functionality to the PHP script.

MyBB uses this the same way that I plan to be able to use it. It allowed them to let people create plugins really easily, and WordPress also uses something very similar.

  • Easy to make additions to certain bits of code.
  • Useful for making plugin systems.
  • Really dynamic in terms of making changes to how a bit of code works.

The main index.php file would look something like the code below. This code is an example, and could be used as part of the site where the header_info hook will display information that needs to be displayed at the start of the script.

Once that file is setup, we can then create a file called app.class.php which will contain our app class that we can then call from anywhere in the script where the file is included. You could also combine this with a router & autoloading script so that you could run & create the hooks wherever you want.

In the index.php file we already run the hook, and as we can see if we don’t create any hooks for header_info it will still continue to run without causing any errors.

We could adapt the index.php file to have a hook that would print out the title of the page, for example you could add:

$app->AddHook('header_info','DisplayTitle');

function DisplayTitle() {
    echo "<title>Amazing Hooks</title>";
}

The above code would give the page a title of Amazing Hooks but this is just a simple example of how this hooks system could be used. Uses for this hooks system are endless!

Facebook
Twitter
LinkedIn
Pinterest
Email