Last active
February 20, 2020 10:35
-
-
Save yoeunes/5cd0cfc8676f03a8b45eb15ba2b288ee to your computer and use it in GitHub Desktop.
Simple example for the Decorator pattern in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Transaction | |
{ | |
public function execute(callable $operation) | |
{ | |
echo 'Begin Transaction', PHP_EOL; | |
$operation(); | |
echo 'Commit Transaction', PHP_EOL; | |
} | |
} | |
interface ServiceInterface | |
{ | |
public function execute(string $request); | |
} | |
class ServiceDecorator implements ServiceInterface | |
{ | |
private ServiceInterface $service; | |
private Transaction $transaction; | |
public function __construct(ServiceInterface $service, Transaction $transaction) | |
{ | |
$this->service = $service; | |
$this->transaction = $transaction; | |
} | |
public function execute(string $request) | |
{ | |
$operation = function () use ($request) { | |
$this->service->execute($request); | |
}; | |
$this->transaction->execute($operation->bindTo($this)); | |
} | |
} | |
class Service implements ServiceInterface | |
{ | |
public function execute(string $request) | |
{ | |
echo $request, PHP_EOL; | |
} | |
} | |
//$service = new Service(); | |
$service = new ServiceDecorator(new Service(), new Transaction()); | |
$service->execute('Execute method run lot of code'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment