Jump to content

When to use $wire, or wire(), or $this??


Vigilante
 Share

Recommended Posts

In general, is there an easy way to know which method should be used to access the API?

For example, when _ini.php is used in the theme, it would seem you have to use wire()->addHookBefore(...). But on other sites where they used ready.php, I've seen it go straight to just doing $this->addHookAfter() even though there is no class or namespace set up in the ready.php file.

So how do I know when I can do $this, or $wire, or wire() to access things? And any other variables I'm not aware of.

Thanks!

Link to comment
Share on other sites

It mostly doesn't matter, you get the same API variables independent of the method. That said, I would suggest the following for readability:

  • $this: Use only inside of classes extending \ProcessWire\Wire. It appears that $this is also available in template files as a reference to the current wire instance, but as you said, this is a somewhat confusing and unconventional usage given that you're not actually inside a class.
  • $wire: Use inside regular PHP template files (or if you want to use a different API variable like $page, $pages, $input, et c. use that one directly).
  • wire(): Use inside functions (not class methods) so you don't have to pass $wire or $this to the closure.
  • Like 5
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

×
×
  • Create New...