您的位置 首页 php

PHP项目如何分离本地、测试和生产环境配置

1.配置 nginx 或Apache的 环境变量

119200023476cc045282

示例代码:

<?php

header (‘Content-Type:text/html;charset=utf-8’);

//根据环境变量定义当前代码部署环境

define (‘RUN_ENV’, isset($_SERVER[‘RUN_ENV’]) ? $_SERVER[‘RUN_ENV’] : ‘product’);

define(‘APP_ROOT’, dirname(dirname(__FILE__)) . ‘/’);

//通过RUN_ENV 宏定义 来引入各个环境的差异配置文件(主要涉及数据库、Memcache、Redis等)

require_once APP_PATH . ‘/conf/’.RUN_ENV.’config.php’;

1)nignx配置示例:

server {

listen 80;

server_name www.google.com;

index index.html index.shtml index.htm index.php;

root /www/www.google.com/html/;

location ~ .*\.php?$

{

proxy_read_timeout 300;

proxy_connect_timeout 300;

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

include fastcgi.conf;

#environment param config

fastcgi_param RUN_ENV ‘develop’;

}

access_log /www/logs/www.google.com.log;

error_log /www/logs/www.google.com.err;

if (!-e $request_filename)

{

rewrite ^/(.+)$ /index.php last;

}

if ( $fastcgi_script_name ~ \..*\/.*php )

{

return 403;

}

}

2)Apache配置示例:

<VirtualHost *:80>

SetEnv RUN_ENV ‘develop’

DocumentRoot “/www/www.google.com/www”

ServerName 127.0.0.10

ServerAlias

<Directory />

Options FollowSymLinks ExecCGI

AllowOverride All

Order allow,deny

Allow from all

</Directory>

</VirtualHost>

不足:这种配置方式仅适用通过Web服务器(nginx或Apache)来访问php脚本的,不适用php-cli模式。

2.设置 php-fpm 的环境变量

env[RUN_ENV] = develop

不足:适用php-fpm模式(一般都是通过Web服务器访问的模式),不适用php-cli模式。

3.通过引入外部私有目录的配置文件

示例代码:

<?php

header(‘Content-Type:text/html;charset=utf-8’);

//根据文件配置定义当前代码部署环境

$run_env_file = “/www/private/www.google.com/config.txt”;

$run_env = file_exists($run_env_file) ? file_get_contents($run_env_file) : ‘product’;

define(‘RUN_ENV’, $run_env );

define(‘APP_ROOT’, dirname(dirname(__FILE__)) . ‘/’);

//通过RUN_ENV宏定义来引入各个环境的差异配置文件(主要涉及数据库、Memcache、Redis等)

require_once APP_PATH . ‘/conf/’.RUN_ENV.’config.php’;

优点:适用各种各样的调用姿势,如php-fpm模式、php-cli模式。

不足:对生产环境的性能有一定影响,因为生产环境的机器如果集群太大的话,我们每个去放这个私有配置文件是特别不划算的,而且我们的原则一般生产环境都是不放的,代码直接实用模式的生产环境配置。但是文件不存在的话,对Linux来说就无法使用文件的页缓存,每次都要进行磁盘I/O去判断文件是否存在,这个性能损耗对生产环境来说特别不友好。一般这种方式作为php-cli模式的补充会更好一点,毕竟php-cli模式一般都是离线在处理一些数据,调用频率也不会特别高。

这里说一下,一般只有本地和测试环境才需要配置这个环境变量,生产环境一般都不用去特殊配置,通过代码默认设置为采用生产环境的配置。本篇文章主要是针对给新手看到哈,不喜勿喷~

文章来源:智云一二三科技

文章标题:PHP项目如何分离本地、测试和生产环境配置

文章地址:https://www.zhihuclub.com/30495.shtml

关于作者: 智云科技

热门文章

网站地图