为了账号安全,请及时绑定邮箱和手机立即绑定

是否有更好的循环遍历这些 PHP 代码的方法,也许使用 foreach 循环?

是否有更好的循环遍历这些 PHP 代码的方法,也许使用 foreach 循环?

PHP
心有法竹 2022-12-23 16:19:04
我file_get_contents用来获取远程定价(每天更新),substr用来只保留我想要的部分(从输出中剥离货币符号和其他数据,只保留数字)并file_put_contents用来将它存储到我引用的缓存目录中到以后。这就是我现在所拥有的:-<?php$cacheDirectory = $_SERVER['DOCUMENT_ROOT'] . '/cache/';// Small Plan - US$cachefile_SM_US = $cacheDirectory . 'SM_US.cache';if(file_exists($cachefile_SM_US)) {    if(time() - filemtime($cachefile_SM_US) > 1600) {        // too old , re-fetch       $cache_SM_US = file_get_contents('https://remotedomain.com/?get=price&product=10&currency=1');        $substr_SM_US = substr($cache_SM_US,17,2);        file_put_contents($cachefile_SM_US, $substr_SM_US);        } else {            // cache is still fresh    }} else {    // no cache, create one    $cache_SM_US = file_get_contents('https://remotedomain.com/?get=price&product=10&currency=1');    $substr_SM_US = substr($cache_SM_US,17,2);    file_put_contents($cachefile_SM_US, $substr_SM_US);}// Large Plan - US$cachefile_LG_US = $cacheDirectory . 'LG_US.cache';if(file_exists($cachefile_LG_US)) {    if(time() - filemtime($cachefile_LG_US) > 1600) {        // too old , re-fetch        $cache_LG_US = file_get_contents('https://remotedomain.com/?get=price&product=20&currency=1');        $substr_LG_US = substr($cache_LG_US,17,2);        file_put_contents($cachefile_LG_US, $substr_LG_US);    } else {        // cache is still fresh    }} else {    // no cache, create one    $cache_LG_US = file_get_contents('https://remotedomain.com/?get=price&product=20&currency=1');    $substr_LG_US = substr($cache_LG_US,17,2);    file_put_contents($cachefile_LG_US, $substr_LG_US);}当只有两种产品 (10和20) 和两种货币 (1和2) 时,这种手动方式有效,因为我只需要这样做 4 次就可以获得我需要的所有定价。但是,我打算将产品数量显着扩大到至少 12 种产品和 9 种货币,因此手动完成它们是不现实的。我相信这可以通过 PHP foreach 循环更有效地完成,但我尝试了几天但没能成功,这可能是因为我对这个概念的理解较弱。
查看完整描述

2 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

绝对地。看看这个例子:)


<?php declare(strict_types=1);


interface CacheNormalizer

{

    public function normalize(string $text): string;

}


interface PlanDomainToCache

{

    public function buildUrl(Plan $plan): string;

}


final class CachedRemoteSiteManager

{

    /** @var int Time To Live Cache */

    private $timeToLive;


    /** @var CacheNormalizer */

    private $cacheNormalizer;


    /** @var PlanDomainToCache */

    private $planDomainToCache;


    public function __construct(

        int $timeToLive,

        CacheNormalizer $cacheNormalizer,

        PlanDomainToCache $planDomainToCache

    ) {

        $this->timeToLive = $timeToLive;

        $this->cacheNormalizer = $cacheNormalizer;

        $this->planDomainToCache = $planDomainToCache;

    }


    public function updateIfNecessary(Plan $plan): void

    {

        if ($this->shouldCreateOrUpdateCache($plan)) {

            $this->createOrUpdateCache($plan);

        }

    }


    private function shouldCreateOrUpdateCache(Plan $plan): bool

    {

        return !file_exists($plan->cacheDirectory())

            || time() - filemtime($plan->cacheDirectory()) > $this->timeToLive;

    }


    private function createOrUpdateCache(Plan $plan): void

    {

        $urlToCache = $this->planDomainToCache->buildUrl($plan);

        $textToCache = file_get_contents($urlToCache);


        file_put_contents(

            $plan->cacheDirectory(),

            $this->cacheNormalizer->normalize($textToCache)

        );

    }

}


final class Plan

{

    /** @var string */

    private $cacheDirectory;


    /** @var int */

    private $product;


    /** @var int */

    private $currency;


    public function __construct(string $cacheDir, int $product, int $currency)

    {

        $this->cacheDirectory = $cacheDir;

        $this->product = $product;

        $this->currency = $currency;

    }


    public function cacheDirectory(): string

    {

        return $this->cacheDirectory;

    }


    public function product(): int

    {

        return $this->product;

    }


    public function currency(): int

    {

        return $this->currency;

    }

}


// Usage example:


$cacheDirectory = $_SERVER['DOCUMENT_ROOT'] . '/cache/';

$productA = 10;

$productB = 20;

$USD = 1;

$EUR = 2;


/** @var Plan[] */

$plansToCache = [

    new Plan($cacheDirectory . 'SM_US.cache', $productA, $USD),

    new Plan($cacheDirectory . 'LG_US.cache', $productB, $USD),

    new Plan($cacheDirectory . 'SM_EU.cache', $productA, $EUR),

    new Plan($cacheDirectory . 'LG_EU.cache', $productB, $EUR),

];


$cacheManager = new CachedRemoteSiteManager(

    $cacheTtl = 1600,

    new class implements CacheNormalizer {

        public function normalize(string $text): string

        {

            return substr($text, 17, 2);

        }

    },

    new class implements PlanDomainToCache {

        public function buildUrl(Plan $plan): string

        {

            return sprintf(

                'https://remotedomain.com/?get=price&product=%d&currency=%d',

                $plan->product(),

                $plan->currency()

            );

        }

    }

);


foreach ($plansToCache as $plan) {

    $cacheManager->updateIfNecessary($plan);

}

正如您在底部看到的,在“使用示例”中,我提取了所有细节(几乎所有细节),因此我们可以轻松定义:

  • 我们要如何规范化缓存数据(使用 CacheNormalizer)

  • 我们要如何构建要缓存的 URL(使用 PlanDomainToCache)。

更新:

如果您想了解如何从结束代码中提取/解耦每个细节,即使对于“持久性”层也向上反转依赖关系:https ://gist.github.com/Chemaclass/01d3f42685ff69f6897192202a32014d


查看完整回答
反对 回复 2022-12-23
?
ITMISS

TA贡献1871条经验 获得超8个赞

如果我正确地解释了代码,您想要查找两种货币的两种产品。这可以在您定义产品和货币后使用嵌套的 foreach 循环来完成。


$cacheDirectory = $_SERVER['DOCUMENT_ROOT'] . '/cache/';

$url = 'https://remotedomain.com/?get=price';


const MAX_CACHE_TIME = 1600;


// Optional

$output = [];


$productList = [

    [

        'id'   => 10,

        'name' => 'SM',

    ],

    [

        'id'   => 20,

        'name' => 'LG',

    ]

];


$currencies = [

    'US' => 1,

    'EU' => 2,

];


foreach ($productList as $product) {

    foreach ($currencies as $currencyName => $currencyId) {

        $cacheFile = $cacheDirectory . $product['name'] . '_' . $currencyName . '.cache';


        if (!file_exists($cacheFile) || filemtime($cacheFile) > MAX_CACHE_TIME) {

            // No cache or too old

            $data = file_get_contents($url . '&product=' . $product['id'] . '&currency=' . $currencyId);

            $relevantData = substr($data, 17, 2);

            file_put_contents($cacheFile, $relevantData);

            // Optional, put the data in an array

            $output[$product['id']][$currencyId] = $relevantData;

        } else {

            $output[$product['id']][$currencyId] = file_get_contents($cacheFile);

        }


    }

}

// Read outputwith $output[10]['US'] for example


查看完整回答
反对 回复 2022-12-23
  • 2 回答
  • 0 关注
  • 136 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号