Last active
December 2, 2020 16:30
-
-
Save nikolaposa/f4d92315b1ffc169015b649559a15fbd to your computer and use it in GitHub Desktop.
New PHP language feature; favor composition over inheritance; `decorates` and `inner` keywords
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 | |
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 | |
} |
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 | |
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