简体   繁体   English

PHP在Composer中使用常量的正确方法

[英]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. 我在packagist.org上有一个PHP库,该库使用一些常量,各个项目之间会有所不同。

I'm trying to use constants like that: 我正在尝试使用这样的常量:

  • Constants stores in conf.php in composer libriary 常量存储在作曲家库中的conf.php

  • 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 composer init username / mylib命令之后,我从/vendor/username/mylib/conf.php复制到本地/conf.php并将其用于当前项目配置

for project1, in /conf.php 对于项目1,在/conf.php中

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

project2, in /conf.php project2,在/conf.php中

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

But it looks like a wrong way. 但这似乎是错误的方式。

What is right way to use constants with composer libraries ? 在作曲家库中使用常量的正确方法是什么?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM