Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do PHP hooks [closed]

Tags:

php

hook

I'm wondering what the best way is of handling hooks in a PHP application
- so I can insert custom or 'plug in' functionality without modifying the main body of code.

I know Wordpress features something like this. Is it really alright to do something as follows:

if (file_exists('file_before'){ include('file_before'); }

print 'hello';

if (file_exists('file_after'){ include('file_after'); }
like image 204
CJD Avatar asked Dec 07 '10 17:12

CJD


2 Answers

How I Usually do things when it comes to hooks is create a HookLoader class which will store two types of hooks, PRE and POST. as PHP Is a single threaded interpreter there would be no such thing as DURING.

Take this example:

$Hooks = new HookLoader();

$Hook->Run("PRE","database_connect");
$Database->Connect();
$Hook->Run("POST","database_connect");

each hook in the hook directory should be name like so:

name_pre_database_connect.hook.php

Hook files would be formatted like so:

{name}_{type}_{event}.hook.php

This will allow you to create unlimited amount of hooks.

preferably i would make hook class abstract and static, this you can just run the hook calls within the actual object, therefore adding new libraries would be integrated as long as they have the Hook::run("type","event");

like image 102
RobertPitt Avatar answered Oct 13 '22 23:10

RobertPitt


Why not use "Observer Pattern" for this? You can add an Object to your body and trigger the actions the attached classed hold. If you want to refine it, you can create a specific method inside each Observer object that defines the stage of the execution. This will likely be more programming at first, but gives a very clean interface for attaching more functionallity to your classes.

For a concrete examample, this IBM dev article (btw its worth reading as a whole) should give you a nice impression of this pattern.

like image 35
DrColossos Avatar answered Oct 13 '22 23:10

DrColossos