We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 22656
    • 121 Posts
    Hi, I have a lot of functions which are duplicated accross various snippets. Is it possible to declare all these functions in one place only and call them from there? What is the best methodology for this?

    create one snippet called [[global-functions]] and stick it at the top?
      • 22303 MODX Staff
      • 10,725 Posts
      You could do that, or create a class to hold your functions and make it available as a "service class" using:
      <?php
      $modx->getService('myservice', 'MyServiceClass', '/path/to/class/', array('param1' => 'value1'));


      Then you can access your methods by simply making this getService() method call in any snippet and accessing your service object like:
      <?php
      $modx->myservice->mymethod();
      


      getService() always returns an existing instance if it’s already been called, so if you call it multiple times from multiple snippets in a single request, you will only be loading the class once.