钩子系统

From Dolibarr Open Source ERP CRM Wiki

返回
开发文档

File Doc dev.png

返回
用户手册

File Doc user.png

返回
首页

File Doc dev.png

Contents

介绍

钩子开发功能,自Dolibarr 3.2开始启用。

允许开发者添加代码到Dolibarr核心区域,而不需要诉诸于修改核心代码。

触发器(与Dolibarr核心代码交互的另一个特性)相反-根据定义,它们链接到业务动作,钩子可以在任何时间任何地方发生,它们是程序的入口点。

  • 钩子的开关位于“内容”(即模块,例如:产品的产品卡,发票的发票卡等)。很容易找到它们,只需搜索(或定位)到PHP文件中的"initHooks("。
  • 钩子是可以由自己的代码完成或替换的代码的一部分。您可以通过搜索(或定位)查找"executeHooks("来找出代码的“可执行”部分。

添加钩子以允许插入代码

要在自己的模块中实现一个钩子(以便其他模块可以“钩住”),你有两个步骤要遵循。

对于要实现钩子的模块的每个PHP脚本,必须遵循这些步骤。当然,这也是钩子在每个核心Dolibarr模块中实现的方式。

1 -初始化HookManager对象(把它放在脚本的开始,在包含之后):

// 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('context'));

$hookmanager->initHooks() takes 1 parameter (an array of contexts) and activate the hooks management for this script:

- 'context' is a context string. This is simply a indicator that hooking functions can use to detect in which context they are called.

Note: you can set several contexts in the same init (for example if you want to have a common context into several pages and want also a specific context deidcated to your page).


2- 放置钩子于你想要引入外部代码之处:

$parameters=array();
$reshook=$hookmanager->executeHooks('hookname',$parameters,$object,$action); // See description below
// Note that $action and $object may have been modified by hook
if (empty($reshook))
{
   ... // standard code that can be disabled/replaced by hook if return code > 0.
}

$hookmanager->executeHooks() takes 4 parameters and add a hook (an entry point in your script for external functions):

- '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:

$parameters=array('file'=>'my/path/to/a/file', 'customnames'=>array('henry','david','john'));

- $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 Implement a hook to implement a hooking function that will take advantage of your new hooks.

实现钩子

To use a hook (add or replace a part of code), you first need to already have defined a module descriptor (see Module_development#Create_your_module_descriptor), and then you need to do 2 things:

1- 将您的模块添加到要钩起的上下文列表中。

This means that when a context you hook will happen, your module hook code will be called. To do that, just edit your /htdocs/yourmodulename/core/modules/modYourModuleName.class.php and edit the $this->module_parts variable with something like this:

$this->module_parts = array(
'hooks' => array('hookcontext1','hookcontext2')  // Set here all hooks context you want to support
);

Of course change YourModuleName with your own module's name.

Note: you can find the current module's context with print('Module context: '.$object->context); (put this inside the module's php file where the hook resides and that you want to hook).

Warning.png Be careful: do not forget to DISABLE then ENABLE the module in the admin panel to accept the new context, because these constants are only added/refreshed to the database when re-enabling your module.


2- 你将用自己的一个钩子(一个函数)重载。

Create a file /htdocs/yourmodulename/class/actions_yourmodulename.class.php and then put something like this:

class ActionsYourModuleName
{ 
	/**
	 * Overloading the doActions function : replacing the parent's function with the one below
	 *
	 * @param   array()         $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    &$object        The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          &$action        Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	function doActions($parameters, &$object, &$action, $hookmanager)
	{
		$error = 0; // Error counter
		$myvalue = 'test'; // A result value
 
		print_r($parameters);
		echo "action: " . $action;
		print_r($object);
 
		if (in_array('somecontext', explode(':', $parameters['context'])))
		{
		  // do something only for the context 'somecontext'
		}
 
		if (! $error)
		{
			$this->results = array('myreturn' => $myvalue);
			$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		}
		else
		{
			$this->errors[] = 'Error message';
			return -1;
		}
	}
}

Your function should now be called when you access the module/context and you will see the parameters and object and action.

Where:

  • $parameters is an array of meta-data about the datas contained by the hook (eg: the context, always accessible by $parameters['context']).
  • $object is the object that you may work on. Eg: the product if you are in the productcard context.
  • $action is the action if one is conveyed (generally "create", "edit" or "view").
  • $hookmanager is propagated only to allow your hook to call another hook.

Returns:

  • The return code from a hook is 0 or 1 if success, negative if error. In general, it will be 0. It can be 1, which means that, in some specific cases, your code hook completely replaces what Dolibarr would do without the hook. If return code is negative, you can also set $this->errors[]='Error message to report to user'
  • If the method sets the property $this->results with an array, then the array $hookmanager->resArray will automatically be enriched with the contents of this array, which can be reused later.
  • If the method sets the property $this->resprints with a string, then this string will be displayed by the hook manager (method executeHook), immediately after your method exit.
  • Your code can also modify the value of $object and $action.

可用钩子列表

How to find a complete list of all available hooks in Dolibarr's nomenclatura ? Just search for "executeHooks(" through the whole sourcecode (generally called "find in files") and you should easily find all the hooked methods calls.

This is however a small list of them (not complete):

  • afterLogin
  • beforePDFCreation
  • afterPDFCreation
  • afterODTCreation
  • createFrom
  • doActions
  • printLeftBlock
  • printSearchForm
  • printTopRightMenu
  • printObjectLine
  • formAddObject: Add a product into an element
  • formObjectOptions: called everytime fields associated to the main object are printed or inputted (eg: creation form, datasheet, edit form, etc..).
  • formConfirm
  • createDictionaryFieldlist
  • editDictionaryFieldlist
  • viewDictionaryFieldlist

...

Note: please note that this list may change in the future as hooks and contexts are added into Dolibarr, so if you really need to find a specific hooks, please search directly in the sourcecode.

可用上下文列表

To find the complete list of available modules' context in Dolibarr's nomenclatura, the procedure is similar to finding hooks. Search for "initHooks(" through the whole sourcecode (generally called "find in files") and you should find all the possible contexts.

This is however a small list of them (not complete): adherents\card.php(111): membercard
adherents\type.php(73): membertypecard
categories\categorie.php(96): categorycard
comm\card.php(72): commcard
comm\propal.php(99): propalcard
comm\action\card.php(85): actioncard
comm\action\index.php(112): agenda
comm\mailing\card.php(55): mailingcard
commande\card.php(93): ordercard
compta\facture.php(105): invoicecard
compta\paiement.php(70): paiementcard
compta\deplacement\card.php(50): tripsandexpensescard
compta\dons\card.php(53): doncard
compta\localtax\clients.php(172): externalbalance
compta\salaries\card.php(47): salarycard
compta\tva\card.php(45): taxvatcard
contact\card.php(77): contactcard
contrat\card.php(70): contractcard
expedition\card.php(85): expeditioncard
fichinter\card.php(80): interventioncard
fourn\card.php(54): suppliercard
fourn\commande\card.php(80): ordersuppliercard
fourn\commande\orderstoinvoice.php(88): orderstoinvoicesupplier
fourn\facture\card.php(72): invoicesuppliercard
fourn\facture\paiement.php(71): paymentsupplier
livraison\card.php(68): deliverycard
product\card.php(91): productcard
product\fournisseurs.php(62): pricesuppliercard
product\stats\commande.php(45): productstatsorder
product\stats\commande_fournisseur.php(45): productstatssupplyorder
product\stats\contrat.php(45): productstatscontract
product\stats\facture.php(48): productstatsinvoice
product\stats\facture_fournisseur.php(47): productstatssupplyinvoice
product\stats\propal.php(45): productstatspropal
product\stock\card.php(54): warehousecard
projet\card.php(48): projectcard
projet\tasks.php(67): projecttaskcard
resource\card.php(60): resource_card
resource\element_resource.php(58): element_resource
societe\agenda.php(41): agendathirdparty
societe\commerciaux.php(40): salesrepresentativescard
societe\consumption.php(80): consumptionthirdparty
societe\info.php(41): infothirdparty
societe\soc.php(80): thirdpartycard
user\card.php(93): usercard
user\passwordforgotten.php(56): passwordforgottenpage
...

Note: please note that this list may change in the future as hooks and contexts are added into Dolibarr, so if you really need to find a specific hooks, please search directly in the sourcecode.

参考

Personal tools
  • Ask to contact@dolibarr.org to request an account to contribute to this documentation
  • Log in
In other languages
<multilanguagemanager_en><multilanguagemanager_fr><multilanguagemanager_es><multilanguagemanager_de>
&lt;multilanguagemanager_notranslation&gt;
<multilanguagemanager_it>
&lt;multilanguagemanager_notranslation&gt;
<multilanguagemanager_el>
&lt;multilanguagemanager_notranslation&gt;

Social networks
Follow us on Google+ Follow us on Facebook Follow us on LinkedIn Follow us on Twitter