PHP項目如何分離本地、測試和生產環境配置

1.配置nginx或Apache的環境變數

示例代碼:

<?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';

Advertisements

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

Advertisements

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模式一般都是離線在處理一些數據,調用頻率也不會特別高。

這裡說一下,一般只有本地和測試環境才需要配置這個環境變數,生產環境一般都不用去特殊配置,通過代碼默認設置為採用生產環境的配置。本篇文章主要是針對給新手看到哈,不喜勿噴~

Advertisements

你可能會喜歡