I’ve written several plugins using the structure :
/plugins/myplugin/myplugin.php
/plugins/myplugin/class/class-myclass.php
So as to take advantage of OO and overall structuring my code
From within the class file there are times I need to get the URL of the base plugin… I have been using the following, but I’m sure there’s a better way:
$this->plugin_location = substr(plugin_dir_url(__FILE__),0, strrpos(plugin_dir_url(__FILE__), "/",-2)) . "/";
Another idea I toyed with was having an additional singleton class that stores all of the settings for the plugin and adding an abstraction layer via the class files.
Any help is greatly appreciated.
In a subdirectory within your plugin directory you can use the following code:
You should make all of your classes independent of their actual location, so you can move them around easily and maybe reuse them in other projects.
I would create a class that tells the other classes what path or URL to use, let it implement an interface so you can reuse the other classes maybe even in a theme or completely outside of WordPress.
Example for the interface:
The concrete implementation in your plugin could look like this:
Now you create an instance of that class in your main plugin file:
And all the other classes have just a dependency on the interface in their constructor, like this:
They are accessing the URL and the path only from the passed instance now.