PHP code example of xbyter / apollo-client

1. Go to this page and download the library: Download xbyter/apollo-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xbyter / apollo-client example snippets


use Xbyter\ApolloClient\ApolloClient;
use Xbyter\ApolloClient\ApolloConfig;
use Xbyter\ApolloClient\ApolloConfigSync;
use Xbyter\ApolloClient\Handlers\ApolloEnvHandler;

define('BASE_PATH', dirname(__DIR__) . '/'); //项目根目录

")
$apolloEnvFile = '.apollo.env';

//解析.env文件
$dotenv = Dotenv\Dotenv::create(__DIR__, $apolloEnvFile);
$dotenv->load();

//阿波罗配置
$apolloConfig = new ApolloConfig();
$apolloConfig->configServerUrl = $_ENV['APOLLO_CONFIG_SERVER_URL'];
$apolloConfig->appId = $_ENV['APOLLO_APP_ID'];
$apolloConfig->cluster = $_ENV['APOLLO_CLUSTER'];
$apolloConfig->secret = $_ENV['APOLLO_SECRET'];


//开始同步配置到.env
$timeout = (int)($argv[1] ?? 0);//定时任务跑一般设置为60,supervisor跑可不设置
$apolloClient = new ApolloClient($apolloConfig);
$handler = new ApolloEnvHandler($sysEnvPath);
$sync = new ApolloConfigSync($apolloClient);
$sync->addHandler($_ENV['APOLLO_NAMESPACE'] ?? 'application', $handler);

//如果需要执行Laravel的artisan config:cache命令,则建议加下下面Handler。
$configCacheHandler = new ApolloArtisanConfigCacheHandler(BASE_PATH);
$sync->addHandler($_ENV['APOLLO_NAMESPACE'] ?? 'application', $configCacheHandler);

//用force方法强制同步配置一次
$sync->force();
//或者常驻执行
$sync->run($_SERVER['SERVER_ADDR'], $timeout);


$apolloClient = new ApolloClient($apolloConfig);
//.env处理器
$handler = new ApolloEnvHandler($sysEnvPath);
$sync = new ApolloConfigSync($apolloClient);
$sync->addHandler($_ENV['APOLLO_NAMESPACE'], $handler);
$sync->addHandler('阿波罗命名空间namespace1', 新的处理器1);//每个namespace都可以有不同/相同的处理方式
$sync->addHandler('阿波罗命名空间namespace1', 新的处理器2);
$sync->addHandler('阿波罗命名空间namespace2', 新的处理器3);

//不限制配置读取方式,依据具体代码实现
APOLLO_CONFIG_SERVER_URL=阿波罗配置同步地址
APOLLO_APP_ID=app
APOLLO_CLUSTER=default
APOLLO_NAMESPACE=application
APOLLO_SECRET=

//以下命令每分钟执行一次,每次会保持住60s进程,在此期间会实时监控配置变更
* * * * * php apollo_config_sync.php 60