Andrei Andrei -3 years ago 137
PHP Question

PHP the right way to use constants with composer

I have a PHP library on, which uses some constants, changing from project to project.

I'm trying to use constants like that:

  • Constants stores in conf.php in composer libriary

  • After composer init username/mylib command, I making a copy from /vendor/username/mylib/conf.php to local /conf.php and use it for current project config

for project1, in /conf.php

define("HOST", "");

project2, in /conf.php

define("HOST", "");

But it looks like a wrong way.

What is right way to use constants with composer libraries ?

Answer Source

I prefer to do this a slightly different way

in my libabry i would have

and provide instructions to copy


then in my code I would have something like

    $sysconffile = static::$vendorbasedir . '/config/system.php';
    if (file_exists($sysconffile)) {
        $sysconf = require $sysconffile;
    } else {
        throw new \RuntimeException('Sys Conf Missing!');

    $localconf = [];
    $localconfile = static::$appbasedir . '/config/local.php';
    if (file_exists($localconfile)) {
        $localconf = require $localconfile;


I also prefer static classes with data over defines, as a define is very loose in documentation, type hinting and over-writable ..

So once i have both config's, I usually do

static::$config = array_replace_recursive($sysconf, $localconf);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download