Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating conditional composer requirements

I've created my first composer package, which has functionality with both MySQL and MongoDB, however, it doesn't require both. I realized that someone may want to use the package just with one of the two databases, and currently I have:

"require": {
    "mongodb/mongodb": "^1.2",
}

I'm trying to figure out, is there a way to make a package optional, and if it exists, to autoload certain files? Or am I better off doing something in my code like:

if (class_exists('PDO')) {
    // Load MySQL code
}
if (class_exists('MongoClient')) {
    // Load MongoDB code
}

Is there another solution I can't thought of?

like image 233
Rohit Avatar asked Oct 22 '25 19:10

Rohit


1 Answers

"Optional" packages manifest themselves as "suggestions" in the composer.json:

"suggest": {
    "mongodb/mongodb":"Required to use this package with Mongo DB",
    "ext-pdo": "Required to use this package with MySQL",
    "ext-pdo_mysql": "Required to use this package with MySQL"
}

Since these are optional, mere suggestions, your code then needs to take care to wrap optional paths in the appropriate conditionals. This might be a test for the PDO class, a test for a connection object of the required types, etc.

like image 62
bishop Avatar answered Oct 24 '25 10:10

bishop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!