Jump to content

Best way to implement a global utility function?

Recommended Posts

Some other frameworks and CMS's I've used have a handy function called "h", which is a shortcut to htmlspecialchars($string, ENT_QUOTES, 'utf-8'). This makes it super-easy to escape output in your templates. I don't see anything like this in ProcessWire, so I'm wondering what is the best way to define a utility function like this that is available to the entire codebase (I intentionally want it to be in the global namespace)? Ideally this would be in my /site/ directory (not /wire/), but it could also be in an installable module I suppose.


Link to post
Share on other sites

I use my own utility function files in my site-profiles in a subfolder called for example: 'mylibs'

I include them once in the site/config.php file:  include_once(dirname(__FILE__) . "/mylibs/myfunctions.php");

This way I can use all what is in my utility files every where, regardless if I run PW in the webserver or if I bootstrap it for CLI operations.

  • Like 6
Link to post
Share on other sites

Yup - horst's solution or an autoload module would work, but I think his would be easier, quicker and upgrade-proof since config.php doesn't get altered during upgrades and has to be included whatever you're doing in ProcessWire.

Link to post
Share on other sites

when it is in the site/config.php it is available everywhere, also in modules, regardless at which time a module is loaded. (I'm speaking of custom modules, especially created just for one site)  :)

I can use all my personal utilities in those modules, in templates, in hanna-codes, just every where at every time, - thanks to Ryan who made $config populated first in PW. (so easy and with less writing)  :)

  • Like 2
Link to post
Share on other sites

For this specific case you could also add hooks to $sanitizer from an autoload module. So that you could call $sanitizer->specialchars(). See wire/core/sanitizer.php for details.

Horst's solution is probably easiest.

On a side note:
There is already $sanitizer->entities() so maybe it would make sense to add specialchars to Sanitizer core class?

  • Like 4
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...