您的位置:58脚本 > php代理模式应用场景 PHP 代理模式

php代理模式应用场景 PHP 代理模式

2023-05-27 03:32 PHP设计模式

php代理模式应用场景 PHP 代理模式

php代理模式应用场景 PHP 代理模式

php代理模式应用场景

目的

为昂贵或者无法复制的资源提供接口。

例子

  • Doctrine2 使用代理来实现框架特性(如延迟初始化),同时用户还是使用自己的实体类并且不会使用或者接触到代理

UML 图

Alt Proxy UML Diagram

代码

BankAccount.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralProxy;

interface BankAccount
{
    public function deposit(int $amount);

    public function getBalance(): int;
}

HeavyBankAccount.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralProxy;

class HeavyBankAccount implements BankAccount
{
    
    private array $transactions = [];

    public function deposit(int $amount)
    {
        $this->transactions[] = $amount;
    }

    public function getBalance(): int
    {
        // this is the heavy part, imagine all the transactions even from
        // years and decades ago must be fetched from a database or web service
        // and the balance must be calculated from it

        return array_sum($this->transactions);
    }
}

BankAccountProxy.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralProxy;

class BankAccountProxy extends HeavyBankAccount implements BankAccount
{
    private ?int $balance = null;

    public function getBalance(): int
    {
        // because calculating balance is so expensive,
        // the usage of BankAccount::getBalance() is delayed until it really is needed
        // and will not be calculated again for this instance

        if ($this->balance === null) {
            $this->balance = parent::getBalance();
        }

        return $this->balance;
    }
}

测试

ProxyTest.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralProxyTests;

use DesignPatternsStructuralProxyBankAccountProxy;
use PHPUnitFrameworkTestCase;

class ProxyTest extends TestCase
{
    public function testProxyWillOnlyExecuteExpensiveGetBalanceOnce()
    {
        $bankAccount = new BankAccountProxy();
        $bankAccount->deposit(30);

        // this time balance is being calculated
        $this->assertSame(30, $bankAccount->getBalance());

        // inheritance allows for BankAccountProxy to behave to an outsider exactly like ServerBankAccount
        $bankAccount->deposit(50);

        // this time the previously calculated balance is returned again without re-calculating it
        $this->assertSame(30, $bankAccount->getBalance());
    }
}


阅读全文
以上是58脚本为你收集整理的php代理模式应用场景 PHP 代理模式全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
© 2024 58脚本 58jiaoben.com 版权所有 联系我们
桂ICP备12005667号-28 Powered by CMS