出于学习目的,我尝试创建一个 GoF Decorator 实现,以将文本转换为压缩文本或加密文本的可能性为例。
<?php
interface DataSource {
public function gerar($texto): string;
public function recuperar($texto) : string;
}
class TextoBase implements DataSource {
public function gerar($texto): string {
return $texto;
}
public function recuperar($texto) : string {
return $texto;
}
}
abstract class Decorator implements DataSource {
private DataSource $decorado;
public function __construct(DataSource $decorado) {
$this->decorado = $decorado;
}
public function gerar($texto): string {
return $this->decorado->gerar($texto);
}
public function recuperar($texto) : string {
return $this->decorado->recuperar($texto);
}
}
class CriptoDecorator extends Decorator {
const KEY = 'vDIa5JdknBqfrKOu8d7UpddnBMCH1vza';
const NONCE = 'Ra5LeH7ntW2rvkz3dmqI5Stx';
public function gerar($texto): string {
return $this->encrypt(parent::gerar($texto));
}
public function recuperar($texto): string {
return $this->decrypt(parent::recuperar($texto));
}
public function encrypt($data) {
return sodium_crypto_secretbox($data, self::NONCE, self::KEY);
}
private function decrypt(string $data): string {
return sodium_crypto_secretbox_open($data, self::NONCE, self::KEY);
}
}
class CompressaoDecorator extends Decorator {
const NIVEL_COMPRESSAO = 6;
public function gerar($texto): string {
return $this->comprimir(parent::gerar($texto));
}
由于某种原因,我收到警告:
Warning: gzuncompress(): data error in C:\wamp64\www\curso\designer_patterns\estrutural\decorator\real_life.php on line 93
那么,有没有办法解决这个问题并允许两个装饰器堆叠并用于 gerar(generate) 和 recuperar(retrieve) ?
白衣非少年