什么叫logic hooks, 这个在这里我就不解释了。sugar wiki 上面有,大家可以自己看,这里重点说logic hooks 实际怎么样用。其实百分之八九十的需求都可以用logic hooks 实现。而这种方法又可以实现 upgrade safe 。(升级不影响功能)着实是十分强大和方便的工具。好了,进入正题。
(1)在sugar 根目录下面有个custom 的目录,子文件夹里面有modules 文件夹,如果之前你用了studio 已经做了一些定制,那么这里已经有一些目录存在了。没错,这些便是模块定制的位置。如图

进入你想定制的模块,如opportunities. 新建文件logic_hooks.php
PHP Code:
<?php
// Do not store anything in this file that is not part of the array or the hook version. This file will
// be automatically rebuilt in the future.
$hook_version = 1;
$hook_array = Array();
// position, file, function
$hook_array['after_save'] = Array();
$hook_array['after_save'][] = Array(1, 'delacc', 'custom/modules/Opportunities/delacc-after_save_mjvn.php','delacc_class', 'delacc_method');
这里的实例是个after_save 事件,也就是每个opportunity save 之后触发的逻辑。
$hook_array['after_save'][] = Array(1, 'delacc', 'custom/modules/Opportunities/delacc-after_save_mjvn.php','delacc_class', 'delacc_method');
这里主要分析的就是这个数组, 它表示了几个主要元素, 第一个参数是index, 这个整型值不用严格定义,第二个便是名称,第三个是你文件的路径,第四个是哪个class 来负责logic hooks, 第四个是实际触发的那个方法。
(2)建立custom/modules/Opportunities/delacc-after_save_mjvn.php' 文件,输入以下代码
PHP Code:
<?php
class delacc_class
{
function delacc_method(&$bean, $event, $arguments=null)
{
if ($event != 'after_save') return;
// Insert your custom logic between these comments
if (isset($bean->sales_stage) && $bean->sales_stage == 'Closed Lost') {
$oppid = $bean->id;
$sql = "select account_id from accounts_opportunities where opportunity_id ='".$oppid."'";
$result = $bean->db->query($sql,true);
if ($bean->db->getRowCount($result)) {
$row = $bean->db->fetchByAssoc($result);
$accountid = $row['account_id'];
}
require_once ('modules/accounts/Account.php');
$account = new Account();
$account->mark_deleted($accountid);
echo "这个客户的账号已经注销!你可以<a href=index.php?module=Opportunities&action=index>返回</a>商业机会列表";
exit;
}
// Insert your custom logic between these comments
}
}
?>
方法接受三个参数,第一个bean 便是当前操作的实例,(自然是opportunity 的一个具体记录)第二个便是事件参数event, 它表示是哪个动作触发的这个hook, 第三个便是自定义参数。
很明显,这个简单的logic 就是保存opportunity 之后判断记录状态,如果是关闭的话,删除对应的account 的帐号。 代码十分的简单。 但却举了个小小的例子。 由此可引申出无数的定制方案。(其实压根不用SQL 来做类似实例这样的事情,也不鼓励直接使用SQL 来操作。在Sugar 里面其实很少需要你写实际SQL 来操作数据,很多已经封装好了。只需要调用对应的成员方法和全局变量便可以实现各种数据的操作 。 )
Logic hooks 如运用得当是十分强大的工具。因为他可以把你的逻辑放入到系统操作的流程当中。
其实此类思想在许多开源系统当中数不胜数, 可以看成是一种观察者设计模式。
Bookmarks