I would like to add http://mobiledetect.net/ class to my template.
Which is the best approach to dynamically use this class in every part(s) of my template?
For the moment I just loaded the class in functions.php like this
function devicecontrol() {
require_once '_/inc/md/Mobile_Detect.php';
}
add_action('wp_loaded', 'devicecontrol', '1');
but to use it, I must first create an instance in every page-template
$detect = new Mobile_Detect;
I know global variables are not a good solution, which is then the best approach to include such classes?
Yes, I heard this sentence a lot of times, but as you experienced, sometimes some variables need to be accessed everywhere.
Some modern PHP frameworks implement advanced patterns like IOC that helps in such type of things, but wordpress lacks in that, and this is the reason a lot of global variables is used in WP.
Generally speaking, in PHP, solutions are:
global
let global vars smell a little less. If you make a thoughtful use, globals doesn’t suck so much. E.g. using them inside functions is not a very bad solution.Strictly related your case, a static method will suffice as alternative to globals, if you just hate them.
Require the file containing the class in your plugin, then
and when you need the
$detect
variable (the mobile detect instance) useMyDetect::$detect
and when you need the$deviceType
variable useMyDetect::$devicType
Edit: an example of usage