Skip to content

Instantly share code, notes, and snippets.

@yoeunes
Last active February 20, 2020 10:35
Show Gist options
  • Save yoeunes/5cd0cfc8676f03a8b45eb15ba2b288ee to your computer and use it in GitHub Desktop.
Save yoeunes/5cd0cfc8676f03a8b45eb15ba2b288ee to your computer and use it in GitHub Desktop.
Simple example for the Decorator pattern in PHP
<?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