Sunday, November 7, 2010

My Two Rules of Logic Hooks

As you may have ascertained from prior posts, something about the logic hooks feature really draws my attention.  I think a lot of it has to do with the fact that the main limit on its capabilities is one's creativity and that power is quite appealing.

Regardless of the reason or the intended purpose of the logic hook, there are a couple of rules that I've learned one should always adhere to in order to avoid problems.

Curious about what they are?  Keep reading.

Rule #1: Always use require_once() instead of require() or include() to reference external files.

All three of these function effectively accomplish the task of allowing you to use external files within your own code.  For example, I might have a PHP script that has some generic functions that I use on a regular basis, such as for the purposes of formatting dates.  Rather than typing that same code every time I need to use it in a script, I can use one of these built in PHP methods to reference that other PHP file and use its code without having to retype any of it.  

So why are there multiple ways of doing the same thing?

The main difference between require_once() and the other two methods is very subtle and is summarized by stating that the latter two methods cause PHP to load the referenced file regardless of whether or not it was loaded earlier in your code.  In contrast, require_once() will load the referenced file only once.  

Within the context of the SugarCRM world, this is a very important point to remember, especially if you are using logic hooks.  The primary reason for using require_once() when using logic hooks is that different actions within SugarCRM may cause multiple logic hooks to fire simultaneously.  A good example of this behavior is the lead conversion process which has the ability to create multiple records at once.  

Using require() or include() will most likely result in errors that usually include the following message:

Class 'some class name' cannot be redeclared.

If you are seeing these type of errors, try using require_once() to resolve it. 

Rule #2: Use unique Class names

For reasons similar to those described for rule #1, unique class names should be used within the PHP file(s) executed by your logic hooks.  This precaution is also for scenarios that may occur within SugarCRM that cause more than one logic hook to trigger simultaneously.

Failing to do so will result in errors similar to the redeclare errors mentioned above.  

No comments:

Post a Comment

Your comments, feedback and suggestions are welcome, but please refrain from using offensive language and/or berating others. Thank you in advance.