search
HomePHP FrameworkLaravelLaravel access Apollo code example

Laravel access Apollo code example

Mar 02, 2019 pm 01:55 PM
apollolaravelphp

The content of this article is about the code examples of Laravel accessing Apollo. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Don’t talk nonsense, just go to the code

<?php /**
 * Created by PhpStorm.
 * User: dehua
 * Date: 2019/3/1
 * Time: 14:17
 */


return [

    &#39;server&#39; => 'http://10.208.204.46:8161',

    'query' => [
        'app_id' => 'wuc',
        'cluster' => 'default',
        'namespace' => 'application',
    ]

];

Daemon process

namespace App\Console\Commands\Apollo;

use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Storage;

class SyncCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ue:apollo:sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '阿波罗同步';

    protected $config = [];

    protected $url;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        $this->url = config('apollo.server') . '/configs/' . implode('/', array_values(config('apollo.query')));
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {


        $this->doSync();
    }


    protected function doSync()
    {

        $client = new Client(['timeout' => 2.00]);

        try {
            $response = $client->request('GET', $this->url);
            $body = json_decode($response->getBody()->getContents(), true);
            $cfg = Arr::get($body, 'configurations', []);
            if (!$cfg) {
                return true;
            }
            $cfg = array_map(function ($value) {
                if ($row = json_decode($value, true)) {
                    return $row;
                }
                return $value;
            }, $cfg);

            $items = [];

            foreach ($cfg as $key => $value) {
                data_set($items, $key, $value);
            }

            foreach ($items as $k => $item) {
                $this->line('Saving ['.$k.']');
                $this->save($k, $item);
            }

        } catch (\Exception $ex) {
            $this->error($ex->getMessage());
        }

    }


    protected function save($fileName, $item)
    {

        if(config('apollo.sync.redis', false)){
            cache()->tags('apollo')->forever($fileName, $item);
            $this->line('Saving To Redis '.$fileName);
        }


        if(config('apollo.sync.file', false)){

            $this->line('Saving To File '.$fileName);

            $fileName = 'apollo/' . $fileName . '.php';
            ksort($item);
            $content = implode("\r\n", [
                "<?php ",
                "return",
                var_export($item, true) . &#39;;&#39;
            ]);

            Storage::disk(&#39;config&#39;)->put($fileName, $content);
        }

        $this->line('==================');
    }
}

The above is the detailed content of Laravel access Apollo code example. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Collaborative Document Editing: Streamlining Workflow in Distributed TeamsCollaborative Document Editing: Streamlining Workflow in Distributed TeamsApr 27, 2025 am 12:21 AM

Collaborative document editing is an effective tool for distributed teams to optimize their workflows. It improves communication and project progress through real-time collaboration and feedback loops, and common tools include Google Docs, Microsoft Teams, and Notion. Pay attention to challenges such as version control and learning curve when using it.

How long will the previous Laravel version be supported?How long will the previous Laravel version be supported?Apr 27, 2025 am 12:17 AM

ThepreviousversionofLaravelissupportedwithbugfixesforsixmonthsandsecurityfixesforoneyearafteranewmajorversion'srelease.Understandingthissupporttimelineiscrucialforplanningupgrades,ensuringprojectstability,andleveragingnewfeaturesandsecurityenhancemen

Leveraging Laravel's Features for Both Frontend and Backend DevelopmentLeveraging Laravel's Features for Both Frontend and Backend DevelopmentApr 27, 2025 am 12:16 AM

Laravelcanbeeffectivelyusedforbothfrontendandbackenddevelopment.1)Backend:UtilizeLaravel'sEloquentORMforsimplifieddatabaseinteractions.2)Frontend:LeverageBladetemplatesforcleanHTMLandintegrateVue.jsfordynamicSPAs,ensuringseamlessfrontend-backendinteg

Can Laravel be used for Full Stack Development (Frontend   Backend)?Can Laravel be used for Full Stack Development (Frontend Backend)?Apr 27, 2025 am 12:10 AM

Laravelcanbeusedforfullstackdevelopment.1)BackendmasterywithLaravel'sexpressivesyntaxandfeatureslikeEloquentORMfordatabasemanagement.2)FrontendintegrationusingBladefordynamicHTMLtemplates.3)EnhancingfrontendwithLaravelMixforassetcompilation.4)Fullsta

What tools help with upgrading to the latest Laravel version?What tools help with upgrading to the latest Laravel version?Apr 27, 2025 am 12:02 AM

Answer: The best tools for upgrading Laravel include Laravel's UpgradeGuide, LaravelShift, Rector, Composer, and LaravelPint. 1. Use Laravel's UpgradeGuide as the upgrade roadmap. 2. Use LaravelShift to automate most of the upgrade work, but it requires manual review. 3. Automatically refactor the code through Rector, and you need to understand and possibly customize its rules. 4. Use Composer to manage dependencies and pay attention to possible dependency conflicts. 5. Run LaravelPint to maintain code style consistency, but it does not solve the functional problems.

Beyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsBeyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsApr 26, 2025 am 12:24 AM

ToenhanceengagementandcohesionamongdistributedteamsbeyondZoom,implementthesestrategies:1)Organizevirtualcoffeebreaksforinformalchats,2)UseasynchronoustoolslikeSlackfornon-workdiscussions,3)Introducegamificationwithteamgamesorchallenges,and4)Encourage

What are the breaking changes in the latest Laravel version?What are the breaking changes in the latest Laravel version?Apr 26, 2025 am 12:23 AM

Laravel10introducesseveralbreakingchanges:1)ItrequiresPHP8.1orhigher,2)TheRouteServiceProvidernowusesabootmethodforloadingroutes,3)ThewithTimestamps()methodonEloquentrelationshipsisdeprecated,and4)TheRequestclassnowpreferstherules()methodforvalidatio

The Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsThe Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsApr 26, 2025 am 12:17 AM

Tomaintainfocusandmotivationinremotework,createastructuredenvironment,managedigitaldistractions,fostermotivationthroughsocialinteractionsandgoalsetting,maintainwork-lifebalance,anduseappropriatetechnology.1)Setupadedicatedworkspaceandsticktoaroutine.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function