We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 10395
    • 96 Posts
    Hi,

    If i want to create a function to use in various snippets/modules, where do i create the function and is there some special way i’d have to call it?

    Thanks.
    • Garry Nutting Reply #2, 18 years ago
      Hi Gaia,

      There’s no special requirements when creating functions etc., you can just create them as you would in normal PHP code.

      You can either include the function within your snippet/module code or separate it out into an include file. It all depends on your application - if it’s a function that will be utilised in more than one snippet/module, then I would recommend going down the include file route.

      If you do create a separate include file, then a tip is to prefix it with the basepath of your install - makes the code more portable across different setups:
      $basePath = $modx->config['base_path'];
      include_once $basePath . 'assets/snippets/mysnippet/functions.inc.php';

      Where you create the files is entirely up to you, but I would recommend that you try and maintain the structure defined in the ’assets’ directory to make life easier in terms of future MODx upgrades.

      Hope that helps, Garry
        Garry Nutting
        Senior Developer
        MODX, LLC

        Email: [email protected]
        Twitter: @garryn
        Web: modx.com
        • 10395
        • 96 Posts
        ah ok i see, thanks for the explination Garry smiley
        • It’s also a good idea to enclose your function in
          if(!function_exists('function-name')) {
          ...
          }
          

          so your snippet can be used more than once on a page.

          http://il.php.net/function_exists
            Studying MODX in the desert - http://sottwell.com
            Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
            Join the Slack Community - http://modx.org