Is there some documentation somewhere that explains what is the life cycle of the plugins?
I’m starting a new plugin with OOP style, and I just found out that my main class is being instanciated a lot (thanks to Xdebug and Netbeans).
I wonder why, and it annoys me because I’m instanciating a Dropbox-API object, and I really didn’t think WordPress would just instanciate my main class that much.
I haven’t found anything related to the plugins life cycle in the Codex nor on Google.
What does ‘OOP style’ means for you? Wrapping all your functions with a class statement? Then you doing it wrong. You missuse the class as namespace.
Huh?
Try it and count the number of files created. If i try it out, there is one file created for each page request. This means, only one instance of the Foo class for each page request.
Let’s try a action call
If I look in my wp-content dir, I found two files. No more. One file is created when the class instance is created. And one is created when the action call is done.
OK, let’s do some stupid things with our instance. Remove the
add_action( 'plugins_loaded', .. )
and add this code instead:How many files do you expect? I expect two. One from the constructor, one from the method.
A new instance is created only when the
new
operator is used.Now I count four files. Two from the constructor and two from the method. This is because WordPress first include the plugin and then do the action hook
plugins_loaded
.Best practice is to use the action hook
plugins_loaded
instead of creating an instance out of a function because, if the plugin file is included anywhere (e.g. in another file of your plugin), a new instance of the class is created everytime the file is included. The action hookplugins_loaded
is done only once for every page request.What might happen is that you pass a copy of you class to a filter or action. For example, if you want to directly modify class variables inside a hook or filter you should also pass the hook by reference
instead of
As is mentioned by bainternet you can also use a singleton pattern to make sure that a specific object is instanciated only once (further calls return the reference to that object).
You could also consider making some functions static (by giving them the static keyword. This is usually done to ‘helper’-like functions which don’t interact with the rest of the class. Static methods can be called without instanciating a class.
You can also pass static functions to an action/filter:
I also checked http://codex.wordpress.org/Plugin_API/Action_Reference and found that plugins can only be loaded at two stages in the request (muplugins_loaded and plugins_loaded).