Jump to content

Best practice: Where to store functions to generate page output


chrizz
 Share

Recommended Posts

Sorry for this confusing headline - I guess it's too late for thinking about this anymore :D

What I want to do:

On a certain page (with a separate assigned template) I want to read some directories from the server and show the contents of the directories on the page.

Now I'm a bit confused where I should place the code the most suitable way

First idea:

just place the code into the template.

=> sounds easy but not "cool"

Second idea:

Write a module, hook the render method and place the code in the module

=> initializing a module on every page which is only needed on one single page seems oversized

Third idea:

Ask the specialists in the forum

=> in every case a good solution ;)

I hope somebody can clarify this and can give me a hint how to solve this problem the "right way".

Thanks in advance!

Chris

Link to comment
Share on other sites

If you need the function multiple times in different contexts (templates, modules... etc.) then you can write a simple module.

Calling a method in your module goes like this:

$myModule = $modules->get('MyModule');
echo $myModule->myFunction();

Advantage: You have access to your module anywhere :)

Module sample code:

class MyModule extends WireData implements Module {

  public static function getModuleInfo() {
  		return array(
			'title' => 'My Module',
			'version' => 100, 
			'summary' => 'ProcessWire is awesome',
			'singular' => true, 
			'autoload' => false, 
			);
  }

  public function init() {
    // Do stuff after an instance of this module is created
  }

  public function myMethod() {
    return 'yeah baby!';
  }

}
  • Like 5
Link to comment
Share on other sites

Using modules for this stuff is nice if you are building functions you'll be re-using on multiple sites. But for the sake of simplicity, I usually put my shared output generation functions just in a common include file like this.

  • Like 2
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...