We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 14883 ☆ A M B ☆
    • 450 Posts
    What’s the best way to structure my code so that I don’t have to write out my database/user/password credentials, create a new xPDO object and do an ->addPackage() on it in every resource/snippet where I need to use my external db xpdo object?

    $myFullyLoadedReadyToGoXPDoObject = ??
    


    It seems like at a minimum I’d have to have two lines - an include statement and a function call. I tried to write a snippet that returned the object, but apparently I’d have to use serialize/unserialize, which requires including the class def. That doesn’t seem any better than including a php file with a function that returns the object, then calling that object.

    Thoughts?


      • 22303 MODX Staff
      • 10,725 Posts
      We generally use a service class to do this; it can then be reused throughout a single request cycle, without having to invoke it multiple times. Just encapsulate the xPDO instantiation (and other global configuration for your connection/package) in the constructor and you can simply do this in your Snippets:
      <?php
      if ($modx->getService('my3pc', 'my3pc.my3pcSerivceClass', '/path/to/model-root/', array('option1' => 'value1')) {
          $modx->my3pc->doSomething();
      }
      ?>