Skip to content

Instantly share code, notes, and snippets.

@nikolaposa
Last active December 2, 2020 16:30
Show Gist options
  • Save nikolaposa/f4d92315b1ffc169015b649559a15fbd to your computer and use it in GitHub Desktop.
Save nikolaposa/f4d92315b1ffc169015b649559a15fbd to your computer and use it in GitHub Desktop.
New PHP language feature; favor composition over inheritance; `decorates` and `inner` keywords
<?php
declare(strict_types=1);
interface UserRepositoryInterface
{
public function find(string $id) : User;
public function findAll() : UserCollection;
}
class DbUserRepository implements UserRepositoryInterface
{
// some implementation...
}
class CachingUserRepository decorates UserRepositoryInterface
{
public function find(string $id) : User
{
$cache = $this->getCache();
if ($cache->has($id)) {
return $cache->get($id);
}
$user = inner::find($id);
$cache->set($id, $user);
return $user;
}
//other methods you don't want to decorate, automatically gets implemented
}
<?php
declare(strict_types=1);
class CachingUserRepository implements UserRepositoryInterface
{
protected $userRepo;
public function __construct(UserRepositoryInterface $userRepo)
{
$this->userRepo = $userRepo;
}
public function find(string $id) : User
{
$cache = $this->getCache();
if ($cache->has($id)) {
return $cache->get($id);
}
$user = $this->userRepo->find($id);
$cache->set($id, $user);
return $user;
}
public function findAll()
{
return $this->userRepo->findAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment