Rohit
Rohit

Reputation: 3137

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?

Upvotes: 4

Views: 1701

Answers (1)

bishop
bishop

Reputation: 39354

"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.

Upvotes: 6

Related Questions