Sunday, January 14, 2018

Adding custom, global, upgrade-safe PHP functions to SugarCRM

PHP Functions
This falls into the category of hard to find.  It is clearly outlined in the SugarCRM Developers Guide but I have never seen anyone use it.  There were no postings on the message boards about it and I simply stumbled upon it one day.  I wanted to consolidate some code written by others, there were functions that were repeated over and over again in module after module.  So I wanted to find a way to easily move these functions into someplace that was shareable by all modules and was upgrade safe.



Custom utils is part of the Extensions framework, the file they are compiled into  'custom/application/Ext/Utils/custom_utils.ext.php' is include()d by the AutoLoader in 'include/entrypoint.php', very early in the loading of the app.  Loading this code so early in the scheme of things can be a great asset, it's a great place to stash all kinds of global stuff.  Of course, stashing all kinds of global stuff can be a bad thing, but when its needed it's my go-to repository.  Also, it loads for both REST and standard (index.php) calls to SugarCRM.

The Code


Files with your functions are stored in custom/Extension/application/Ext/Utils/For this it does not matter what you neame the files, but like everything in custom/extensions keep your file names as unique as you can.  I keep my files segregated by function so I have a file with User utils in it and a file with field level functions in it and so on.   These files will be 'compiled' into one file by the infamously misnamed Quick repair and Rebuild.  An example of one of my files might be


This file makes my code more readable by eliminating all the 
from my code.  It's much easier to read and understand this
So other things you might store here might be constants
I use this because it is far easier to understand UNASSIGNED_USER than if you are looking at a GUID.  There is no reason I can think of that you couldn't include classes here as well.  I havnt run across a use case for it yet but it's possible.

No comments:

Post a Comment