开发者

Best way to do PHP hooks [closed]

As it currently stands, this question is not a good fit for our Q&A form开发者_StackOverflowat. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago.

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'); }


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");


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.


MediaWiki has their own mechanism of defining hooks in their methods, and ways of registering functions to be executed for a given point of execution...

http://www.mediawiki.org/wiki/Hooks (might be a good place to start)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜