Hooks system: Difference between revisions

Adding implementation of a hook
(→‎Implementation: rename to Usage and fix some mistakes)
(Adding implementation of a hook)
Line 6: Line 6:
* Hooks are functions that can be overloaded by your own. You decide if your code is added to standard Dolibarr code or if it replace Dolibarr code. You can find overloadable functions by searching for "'''executeHooks('''"
* Hooks are functions that can be overloaded by your own. You decide if your code is added to standard Dolibarr code or if it replace Dolibarr code. You can find overloadable functions by searching for "'''executeHooks('''"


= Implementation =
To implement a hook in your own module (so that your module can be ''hooked'' by others), you have two steps to follow.
These steps must be followed for every php script of your module where you want to implement hooks.
1- Initialize the HookManager object (put this in the beginning of your script, just after includes):
<source lang="php">
// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
include_once(DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php');
$hookmanager=new HookManager($db);
$hookmanager->initHooks(array('actioncard'));
</source>
2- Place hooks wherever you want in your script:
<source lang="php">
$parameters=array();
$reshook=$hookmanager->executeHooks('hookname',$parameters,$object,$action); // See description below
// Note that $action and $object may have been modified by hook
</source>
'''$hookmanager->executeHooks()''' takes 4 parameters:
- ''''hookname'''' is the hook's name as a string (can be anything you want, or you can follow the Dolibarr's nomenclatura, look at the list of hooks below). eg: 'formObjectOptions'
- '''$parameters''' is a custom array to send more custom data to the hook (the hooking function can then process it). Place here anything you want, it can be a file, an array of strings, anything...
eg:
<source lang="php">
$parameters=array('file'=>'my/path/to/a/file', 'customnames'=>array('henry','david','john'));
</source>
- '''$object''' is the object you want to pass onto the hooking function, mainly the current module's data (eg: invoice object if it is invoice module, etc..). This can be anything you want, but remember this will be the main component hooking functions will be using.
- '''$action''' is a string indicating the current action (can be set to null or to something sensible like 'create' or 'edit').
Note: You will want to redo this step if you want to add multiple hooks at different places in your script.
Now your module should be hookable, and you can follow the procedure below in '''Usage''' to implement a hooking function that will take advantage of your new hooks.
Note2: If your hook can't be accessed, try to DISABLE then RENABLE your module for the hooks to be taken in account by Dolibarr (may not be required).


= Usage =
= Usage =
439

edits