I was wondering if there is a way to load different folder based on php version. I could do it writing my own autoloader, but i was wondering if there is a way of using composer for that?
Ps. I have seen this in use before in module / plugin application that where redistributed globally to work with wide range of env. Those scripts where using own autoloading classes.
I am curios is there a way to use composer in similar way.
Scenario: class / folder structure:
class >
php5.6 >
- SomeClass.php
...
php7.x >
- SomeClass.php
...
php8.x >
- SomeClass.php
...
Compare php version and do something:
$classPathForAutoloader = '';
if (version_compare(PHP_VERSION, '8.0.0') >= 0) {
$classPathForAutoloader = 'php8.x';
// do something to composer autoload or
// use declaration
}else if(version_compare(PHP_VERSION, '7.0.0') >= 0){
$classPathForAutoloader = 'php7.x';
// do something to composer autoload or
// use declaration
}else if(version_compare(PHP_VERSION, '5.6.0') >= 0{
$classPathForAutoloader = 'php5.6';
// do something to composer autoload or
// use declaration
}else{
// throw Exception ...
}
standard composer setup:
{
"name": "some/name",
"require": {
},
"authors": [
{
"name": "Some Name",
"email": "[email protected]"
}
],
"autoload": {
"psr-4": {
"Devwl\": "class/",
"Tools\": "tools/"
},
"classmap": [
"class/"
],
"exclude-from-classmap": []
}
}
2
Answers
So i have created a class which does what I need. It can laso work alongside Composer autoloader.
Use the PhpVersionAutoloader object like this:
I also created more functional class of this loader which allow to force specific directory to load from or even allow to load classes from older version of PHP if not found in selected version.
See github [here]
I don’t think Composer provides a way to dynamically autoload different paths.
Can you use
version_compare
in a singleSomeClass.php
class only where the functionality differs by PHP version? Or write the entireSomeClass.php
to be backwards compatible?To me loading different classes depending on the PHP version is asking for trouble when it comes to reproducibility across environments.
Another option would be to use
require_once
to load the different classes, but for maintainability I’d really lean towards a single class with version checks only when absolutely necessary.