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

    I’m just trying to code my first own snippet (which will output stored emergency service dates of different doctors and drug stores).

    I got a question concerning the scope of "my" variables. My snippet code in the manager is just a "require file.php" and the real programming is done in external files. The variables that I use, are they all global? Should I capsule the snippet’s code in functions to make my variables local and to avoid interference with other snippets, plugins or core code?

    Thanks for your thoughts
    Martin
      • 22303 MODX Staff
      • 10,725 Posts
      Snippets are eval()’d with an output buffer, so everything within the scope of the eval should be available to your included code. I generally include my snippets from the file system anyway, to reduce the siteCache file size, and make it easy to deploy changes by FTPing code I edit in an IDE. e.g.
      <?php
      return include (MODX_BASE_PATH . 'assets/snippets/opengeek/mysnippetfile.php');
      ?>

      My snippet includes simply return the output (if any, empty string otherwise). You can wrap it in another output buffer if you want to capture output from echo/print statements.

      I generally put functions and other reusable code that I may need to use more than once on a page into class or function files which I require_once().
        • 10313
        • 375 Posts
        I think that’s exactly what I do. I have a link to a file that I code within eclipse. I then only need to upload my files but not change the snippet code in modX. Is it okay when I use echo to generate code for the output or should I do it by return value?

        Thx for your tipps
        Martin
          • 22303 MODX Staff
          • 10,725 Posts
          Quote from: FuryDE at Jun 21, 2007, 03:32 PM

          Is it okay when I use echo to generate code for the output or should I do it by return value?

          You can capture echo and other stdout by simply wrapping the include in, and capturing the content from, an additional output buffer, e.g. something like so...
          <?php
          ob_start();
          $includeResults= include (MODX_BASE_PATH . 'assets/snippets/somesnippetthatechoescontent.php');
          $contentOutput= ob_get_contents();
          ob_end_clean();
          return $contentOutput;
          ?>
          
            • 10313
            • 375 Posts
            Oh, I just noticed that this is NOT exactly what i was doing. But now I do. The last code you posted is that in the modX snippet, right? And I do my coding in the included file. Looks nice.

            Thanks again
            Martin