Andrei Andrei - 1 year ago 67
PHP Question

PHP the right way to use constants with composer

I have a PHP library on packagist.org, 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", "host1.com");


project2, in /conf.php

define("HOST", "host2.com");


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
/vendor/vendorname/pkg/config/system.php
/vendor/vendorname/pkg/config/local.sample.php

and provide instructions to copy

/vendor/vendorname/pkg/config/local.sample.php
to
/config/local.php

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;
    }

UPDATE:

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