Jump to content

How To -- Global Object / Dependency Injection


Jim Bailie
 Share

Recommended Posts

Hello - So I have this object that needs to run on every page load or ajax call. What's the PW way of making this object available?

I've pretty much landed on either putting it into a module OR adding it to the wire function.

I will say, I'm a little rusty on my OO PHP skills, so if anyone could talk me through either scenario or can offer a past post/example, I'd be grateful.

Link to comment
Share on other sites

@Jim Bailie In addition to the options you mentioned, if you put $myObject = new MyObject(); in your /site/templates/_init.php, then $myObject will also be available to all the page templates and the _main.php file, i.e. echo $myObject->value; As a benefit, it'll be automatically excluded from template files that don't use _init.php, such as the admin.php template file. 

If it's something that you might need on every page/template, but not necessarily, you may want to use it as a function in /site/ready.php that constructs it on first access, and then returns the same object on any later accesses to the function:

function myObject() {
  static $myObject = null;
  if($myObject === null) $myObject = new MyObject();
  return $myObject;
}

In this case, you'd use it like as a function with () appended rather than $ prepended, i.e. echo myObject()->value; This also has the benefit of using the same object (rather than creating another) if you happen to be calling $page->render(); on other pages in your template file(s). 

Another option: The way that ProcessWire does it is to use API variables, and you can add your own if you want. If you go that route, put in your /site/ready.php file:

$wire->wire('myObject', new MyObject()); 

Then $myObject is available in any template files. The downside here is that it'll also be available to template files where you might not need it, such as the admin.php template file. So you may want to create it conditionally:

if($page->template->name != 'admin') {
  $wire->wire('myObject', new MyObject()); 
}
  • Like 10
  • Thanks 1
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...