Share
Embed
Hackで作る堅実な アプリケーションアーキテクチャ / Hack-application-architecture
PHP Conference Sendai 2019で利用したスライドです
yuuki takezawa
January 22, 2019
Transcript
154 slides
-
Profile • ᖒ ༗و / ytake • גࣜձࣾΞΠελΠϧ CTO •
PHP, Hack, Go, Scala • Apache Hadoop, Apache Spark, Apache Kafka • twitter https://twitter.com/ex_takezawa • facebook https://www.facebook.com/yuuki.takezawa • github https://github.com/ytake -
Agenda • PHP Array / Hack Arrays • Shapes In
Hack • Generics (With Dependency Injection) • Trait And Interface Requirements • Implementing DDD / Generic Repository -
Notice • PHPޓ͕αϙʔτ͞ΕΔ࠷ޙͷόʔδϣϯ • hhvm.enable_php=false PHPίʔυΛແޮԽ • HackTestCLIɺIOपΓͷϥΠϒϥϦ͕ॆ࣮ •
HHVMͰPHPΛಈ࡞ͤ͞ΔΑΓHackͱͯ͠ -
Hack ϥΠϒϥϦ • facebook/hack-router Hackઐ༻ϧʔλʔ • facebook/hh-clilib CLIϥΠϒϥϦ • usox/hackttp
Hack HTTPΠϯλʔϑΣʔε࣮ • ytake/hungrr Hack HTTPΠϯλʔϑΣʔε࣮ • hhpack/service-locator αʔϏεϩέʔλʔɾDI • nazg/glue αʔϏεϩέʔλʔɾDI • nazg/heredity ϛυϧΣΞσΟεύονϟ • nazg/hcache Ωϟογϡ -
<?php declare(strict_types=1); class ArraySet { protected $collect = []; public
function add(string $key, string $value): void { $this->collect[$key] = $value; } public function all(): array { return $this->collect; } } -
<?php declare(strict_types=1); class ArraySet { protected $collect = []; public
function add(string $key, string $value): void { $this->collect[$key] = $value; } public function all(): array { return $this->collect; } } ෆ࣮֬ͳܕͷࠞೖΛ͙ͨΊ ೖྗΛ੍ݶ -
<?php declare(strict_types=1); class ArraySet { protected $collect = []; public
function add(string $key, string $value): void { $this->collect[$key] = $value; } public function all(): array { return $this->collect; } } ੍ޚෆՄ -
class ExtendArraySet extends ArraySet { public function all(): array {
$this->collect[1] = 2; return $this->collect; } } ੍ޚෆՄ -
<?hh // strict class ArraySet { protected darray<string, string> $collect
= []; public function add(string $key, string $value): void { $this->collect[$key] = $value; } public function all(): darray<string, string> { return $this->collect; } } -
<?hh // strict class ArraySet { protected darray<string, string> $collect
= []; public function add(string $key, string $value): void { $this->collect[$key] = $value; } public function all(): darray<string, string> { return $this->collect; } } ෆ࣮֬ͳܕͷࠞೖΛ͙ͨΊ ೖྗΛ੍ݶ -
<?hh // strict class ArraySet { protected darray<string, string> $collect
= []; public function add(string $key, string $value): void { $this->collect[$key] = $value; } public function all(): darray<string, string> { return $this->collect; } } ܧঝ࣌Ͱͦͷ··੍ޚՄ -
class ExtendArraySet extends ArraySet { public function all(): darray<string, string>
{ $this->collect[1] = 2; return $this->collect; } } ૠೖෆՄ -
class ExtendArraySet extends ArraySet { public function all(): darray<string, string>
{ $this->collect[1] = 2; return $this->collect; } } ΓͷܕΛมߋ͢Δ͜ͱෆՄ -
src/ArraySet.php:19:5,25: Invalid assignment (Typing[4110]) src/ArraySet.php:5:20,25: This is a string src/ArraySet.php:19:20,20:
It is incompatible with an int src/ArraySet.php:20:12,25: Invalid return type (Typing[4110]) src/ArraySet.php:18:33,38: This is a string src/ArraySet.php:19:20,20: It is incompatible with an int -
public function merge(): darray<mixed, mixed> { $a = new ArraySet();
$a->add('PHP', 'Arrays'); $ar = $a->all(); $ar[1] = 11; return $ar; } औಘޙɺ ҟͳΔܕͷΛࠞೖͤ͞Δ͜ͱՄೳ *ΓͷܕΛఆٛ͢Δ͜ͱ -
PHP Style Arrays • array ௨ৗͷྻ • varray ͷΈͰߏ͞ΕΔྻ •
darray σΟΫγϣφϦͷྻ -
<?hh // strict class Sample { protected varray<string> $varray =
varray[ 'php', 'hack' ]; protected darray<int, string> $darray = darray[ 'testing' => 'testing', 1 => 'testing' ]; public function failedVArray(): varray<int> { return $this->varray; } public function getDArray(): darray<string, string> { return $this->darray; } } -
<?hh // strict class Sample { protected varray<string> $varray =
varray[ 'php', 'hack' ]; protected darray<int, string> $darray = darray[ 'testing' => 'testing', 1 => 'testing' ]; public function failedVArray(): varray<int> { return $this->varray; } public function getDArray(): darray<string, string> { return $this->darray; } } ܕҧ͍ -
<?hh // strict class Sample { protected varray<string> $varray =
varray[ 'php', 'hack' ]; protected darray<int, string> $darray = darray[ 'testing' => 'testing', 1 => 'testing' ]; public function failedVArray(): varray<int> { return $this->varray; } public function getDArray(): darray<string, string> { return $this->darray; } } Γͷܕҧ͍ -
<?hh // strict class Sample { protected varray<string> $varray =
varray[ 'php', 'hack' ]; protected darray<int, string> $darray = darray[ 'testing' => 'testing', 1 => 'testing' ]; public function failedVArray(): varray<int> { return $this->varray; } public function getDArray(): darray<string, string> { return $this->darray; } } Γͷܕҧ͍ -
<?hh // strict class ArraySet { protected dict<string, string> $collect
= dict[]; public function add(string $key, string $value): void { $this->collect[$key] = $value; } public function all(): dict<string, string> { return $this->collect; } } dictࢦఆ -
Hack Arrays • Hack Arrays isԋࢉࢠ(HackͷΈͷԋࢉࢠ)Λ༻͍ͯఆՄೳ $dict is dict<_, _>
, etc • Hack ArraysͦΕͧΕͷྻʹมՄೳ (Collection͔ΒHack Arraysͦͷٯ) -
$vec = vec[1,1,2,3,4,5,6,6,7,8]; var_dump($vec); var_dump(dict($vec)); var_dump(keyset($vec)); $dict = dict[1 =>
2, 3 => 'testing']; var_dump(vec($dict), $dict is dict<_, _>); -
abstract final class dict<+Tk as arraykey, +Tv> implements Indexish<Tk, Tv>,
XHPChild {} abstract final class keyset<+T as arraykey> implements Indexish<T, T>, XHPChild {} abstract final class vec<+T> implements Indexish<int, T>, XHPChild {} -
class CollectionSet { protected Map<string, string> $collect = Map{}; public
function add(string $key, string $value): void { $this->collect[$key] = $value; } public function all(): Map<string, string> { return $this->collect; } } Mapࢦఆ -
class CollectionSet { protected Map<string, string> $collect = Map{}; public
function add(string $key, string $value): void { $this->collect[$key] = $value; } public function all(): Map<string, string> { return $this->collect; } } ྻͱಉ͡Α͏ʹૠೖ -
Notice: Hack Arrays / Collections • HackͰissetɺunsetར༻Ͱ͖ͳ͍ • unsetremoveɺfilter(Collection) hhvm/hslΛར༻͢Δ͜ͱ
• issetcontains(Collection)array_key_existsɺ hhvm/hslར༻ -
class HackMap { protected Map<string, string> $collect = Map{ 'a'
=> 'b', 'c' => 'd', }; public function filterRemove( string $keyName ): Map<string, string> { return $this->collect ->filterWithKey(($key, $_) ==> $key !== $keyName); } public function remove( string $keyName ): Map<string, string> { return $this->collect->remove($keyName); } } ࢦఆͨ͠ΩʔҎ֎ͷͷΛ MapͰฦ٫ -
class HackMap { protected Map<string, string> $collect = Map{ 'a'
=> 'b', 'c' => 'd', }; public function filterRemove( string $keyName ): Map<string, string> { return $this->collect ->filterWithKey(($key, $_) ==> $key !== $keyName); } public function remove( string $keyName ): Map<string, string> { return $this->collect->remove($keyName); } } ࢦఆͨ͠ΩʔΛআ͠ɺ MapͰฦ٫ -
Hack Arrays / Collections • array͚ͩͰ੍ݶͰ͖ͳ͍ͷΛ੍ݶ • PHP͔ΒҠߦ͢Δ߹·͔ͣ͜͜Β Ұ൪ޮՌ͕େ͖͍ •
arrayૢ࡞ͱ΄΅ಉ͡ͰɺͦΕΒͷPHP͕ؔར༻Մ -
<?php declare(strict_types=1); class GenerateArrayField { public function getArray(): array {
return [ 'q' => 'qwerty', 'w' => 'wertyu', ]; } } -
<?php declare(strict_types=1); class GenerateArrayField { public function getArray(): array {
return [ 'q' => 'qwerty', 'w' => 'wertyu', ]; } } ྻͷϑΟʔϧυʹରͯ͠ ੍ݶෆՄ -
<?hh // strict type SampleShape = shape('q' => string, 'w'
=> string); class GenerateArrayField { public function getArray(): SampleShape { return shape( 'q' => 'qwerty', 'w' => 'wertyu', ); } } -
<?hh // strict type SampleShape = shape('q' => string, 'w'
=> string); class GenerateArrayField { public function getArray(): SampleShape { return shape( 'q' => 'qwerty', 'w' => 'wertyu', ); } } ྻͷϑΟʔϧυʹܕఆٛ -
<?hh // strict type SampleShape = shape('q' => string, 'w'
=> string); class GenerateArrayField { public function getArray(): SampleShape { return shape( 'q' => 'qwerty', 'w' => 'wertyu', ); } } shapeΛͬͯهड़ -
public function getArrays(): vec<SampleShape> { return vec[ shape('q' => 'qwerty',
'w' => 'wertyu',), shape('q' => 'PHP', 'w' => 'Hack',), shape('q' => 'Java', 'w' => 'Scala',), ]; } vecྻʹshapesΛ Έ߹ΘͤͯΑΓ࣮֬ͳྻ -
namespace Acme\Shapes; type SampleShape = shape( 'a' => int, 'b'
=> int ); type NestShape = shape( 'sample' => SampleShape, 'vec' => vec<string> ); class NestedShape { public function nest(): NestShape { return shape( 'sample' => shape( 'a' => 0, 'b' => 1 ), 'vec' => vec[ 'shapes' ], ); } } Shapesಉ࢜ΛΈ߹Θͤͯ ఆٛՄ -
The field 'z' is not defined in this shape type,
and this shape type does not allow unknown fields. The field 'z' is set in the shape. ఆٛ͞Ε͍ͯͳ͍ϑΟʔϧυ ར༻࣌ʹΤϥʔ -
class HalShape { const type embeddedLinks = shape( 'name' =>
string, '_links' => shape( 'self' => shape( 'href' => string ) ) ); public function index(): void { $url = [ 'name' => 'hack', '_links' => [ 'self' => [ 'href' =>'uri' ] ] ]; \var_dump($url as this::embeddedLinks); } } -
class HalShape { const type embeddedLinks = shape( 'name' =>
string, '_links' => shape( 'self' => shape( 'href' => string ) ) ); public function index(): void { $url = [ 'name' => 'hack', '_links' => [ 'self' => [ 'href' =>'uri' ] ] ]; \var_dump($url as this::embeddedLinks); } } type constantsΛͬͯ shapeΛهड़ -
class HalShape { const type embeddedLinks = shape( 'name' =>
string, '_links' => shape( 'self' => shape( 'href' => string ) ) ); public function index(): void { $url = [ 'name' => 'hack', '_links' => [ 'self' => [ 'href' =>'uri' ] ] ]; \var_dump($url as this::embeddedLinks); } } ྻͳͲͰΛهड़ -
class HalShape { const type embeddedLinks = shape( 'name' =>
string, '_links' => shape( 'self' => shape( 'href' => string ) ) ); public function index(): void { $url = [ 'name' => 'hack', '_links' => [ 'self' => [ 'href' =>'uri' ] ] ]; \var_dump($url as this::embeddedLinks); } } shapeͷఆٛΛݩʹྻΛݕࠪ -
$container = new Container(); $container->set( \stdClass::class, ($container) ==> new \stdClass()
); $stdClass = $container->getInstance(\stdClass::class); ೖྗΛΫϥε໊ͷΈͱ੍ͯ͠ݶ -
$container = new Container(); $container->set( \stdClass::class, ($container) ==> new \stdClass()
); $stdClass = $container->getInstance(\stdClass::class); Typechecker͕ఆͰ͖ͳ͍߹ɺ isͳͲΛར༻ͯ͠อূ͢Δඞཁ͕͋Δ -
<?hh // strict namespace Acme; use namespace HH\Lib\{C, Str}; class
Container<T> { private dict< string, (Scope, (function(\Acme\Container<T>): T)) > $map = dict[]; public function set( classname<T> $id, (function(\Acme\Container<T>): T) $callback, Scope $scope = Scope::PROTOTYPE, ): void { $this->map[$id] = tuple($scope, $callback); } -
<?hh // strict namespace Acme; use namespace HH\Lib\{C, Str}; class
Container<T> { private dict< string, (Scope, (function(\Acme\Container<T>): T)) > $map = dict[]; public function set( classname<T> $id, (function(\Acme\Container<T>): T) $callback, Scope $scope = Scope::PROTOTYPE, ): void { $this->map[$id] = tuple($scope, $callback); } Genericsར༻ -
<?hh // strict namespace Acme; use namespace HH\Lib\{C, Str}; class
Container<T> { private dict< string, (Scope, (function(\Acme\Container<T>): T)) > $map = dict[]; public function set( classname<T> $id, (function(\Acme\Container<T>): T) $callback, Scope $scope = Scope::PROTOTYPE, ): void { $this->map[$id] = tuple($scope, $callback); } dictΛར༻͠ɺ ίʔϧόοΫͰTΛฦ٫͢Δͱఆٛ -
<?hh // strict namespace Acme; use namespace HH\Lib\{C, Str}; class
Container<T> { private dict< string, (Scope, (function(\Acme\Container<T>): T)) > $map = dict[]; public function set( classname<T> $id, (function(\Acme\Container<T>): T) $callback, Scope $scope = Scope::PROTOTYPE, ): void { $this->map[$id] = tuple($scope, $callback); } classname<T> ͭ·Γଘࡏ͢ΔΫϥε໊ͷΈڐՄͱ͢Δ -
<?hh // strict namespace Acme; use namespace HH\Lib\{C, Str}; class
Container<T> { private dict< string, (Scope, (function(\Acme\Container<T>): T)) > $map = dict[]; public function set( classname<T> $id, (function(\Acme\Container<T>): T) $callback, Scope $scope = Scope::PROTOTYPE, ): void { $this->map[$id] = tuple($scope, $callback); } tupleͰΠϯελϯεੜํ๏ͱɺ ίʔϧόοΫΛอ࣋ -
<<__Rx>> public function getInstance(classname<T> $t): T { return $this->resolve($t); }
<<__Memoize>> protected function shared(classname<T> $id): T { list($_, $callable) = $this->map[$id]; return $callable($this); } <<__Rx>> public function has(string $id): bool { return C\contains_key($this->map, $id); } -
<<__Rx>> public function getInstance(classname<T> $t): T { return $this->resolve($t); }
<<__Memoize>> protected function shared(classname<T> $id): T { list($_, $callable) = $this->map[$id]; return $callable($this); } <<__Rx>> public function has(string $id): bool { return C\contains_key($this->map, $id); } hhvm/hsl array_key_existsϥούʔؔ -
<<__Rx>> public function getInstance(classname<T> $t): T { return $this->resolve($t); }
<<__Memoize>> protected function shared(classname<T> $id): T { list($_, $callable) = $this->map[$id]; return $callable($this); } <<__Rx>> public function has(string $id): bool { return C\contains_key($this->map, $id); } ϝϞԽࢦఆ ҾΛར༻ͯ͠Ωϟογϡ͞ΕΔ γϯάϧτϯ -
<<__Rx>> public function getInstance(classname<T> $t): T { return $this->resolve($t); }
<<__Memoize>> protected function shared(classname<T> $id): T { list($_, $callable) = $this->map[$id]; return $callable($this); } <<__Rx>> public function has(string $id): bool { return C\contains_key($this->map, $id); } reactiveʹ -
<<__Rx>> protected function resolve(classname<T> $id): T { if ($this->has($id)) {
list($scope, $callable) = $this->map[$id]; if ($callable is nonnull) { if ($scope === Scope::SINGLETON) { return $this->shared($id); } return $callable($this); } } throw new Exception\NotFoundException( Str\format('Identifier "%s" is not binding.', $id), ); } -
<<__Rx>> protected function resolve(classname<T> $id): T { if ($this->has($id)) {
list($scope, $callable) = $this->map[$id]; if ($callable is nonnull) { if ($scope === Scope::SINGLETON) { return $this->shared($id); } return $callable($this); } } throw new Exception\NotFoundException( Str\format('Identifier "%s" is not binding.', $id), ); } nullͰͳ͍͔Ͳ͏͔ -
<<__Rx>> protected function resolve(classname<T> $id): T { if ($this->has($id)) {
list($scope, $callable) = $this->map[$id]; if ($callable is nonnull) { if ($scope === Scope::SINGLETON) { return $this->shared($id); } return $callable($this); } } throw new Exception\NotFoundException( Str\format('Identifier "%s" is not binding.', $id), ); } γϯάϧτϯͷ߹ɺ ϝϞԽ -
/** * Fire an event when a lockout occurs. *
* @param \Illuminate\Http\Request $request * @return void */ protected function fireLockoutEvent(Request $request) { event(new Lockout($request)); } /** * Get the rate limiter instance. * * @return \Illuminate\Cache\RateLimiter */ protected function limiter() { return app(RateLimiter::class); } -
ෳࡶͳґଘؔ • Laravelͷ app ϔϧύʔؔ αʔϏείϯςφ(DIίϯςφ)ʹΞΫηε͕Ͱ͖Δͷ • τϨΠτͱͷґଘ͕ؔ͋ΔԿ͔ͷॲཧͷதͰɺ Πϯελϯεੜʹ͍ͭͯͷอূ͕Ͱ͖ͳ͍ͨΊɺ DIίϯςφʹάϩʔόϧΞΫηεΛ
ߦ͍ΠϯελϯεΛऔಘ͢Δɺ ͱ͍͏αʔϏεϩέʔλґଘΛӅṭ -
<?hh // strict namespace Acme; trait MessageTrait { require implements
RequestInterface; private dict<string, vec<string>> $headers = dict[]; } -
<?hh // strict namespace Acme; trait MessageTrait { require implements
RequestInterface; private dict<string, vec<string>> $headers = dict[]; } ࢦఆͨ͠ΠϯλʔϑΣʔεΛ࣮ ͨ͠ΫϥεͷΈʹར༻Λ੍ݶ -
src/Request.php:6:7,18: Failure to satisfy requirement: Acme\RequestInterface (Typing[4111]) src/MessageTrait.php:6:22,37: Required here
ΠϯλʔϑΣʔεΛ࣮͍ͯ͠ͳ͍ Ϋϥεʹهड़ͨ͠߹ɺ ΤϥʔͱͳΓ·͢ -
<?hh // strict namespace Acme; class Request implements RequestInterface {
use MessageTrait; protected function getVersion(): string { return '1.1'; } } -
trait MessageTrait { require implements RequestInterface; private dict<string, vec<string>> $headers
= dict[]; public function castIntVersion(): int { return (int) $this->getVersion(); } } -
trait MessageTrait { require implements RequestInterface; private dict<string, vec<string>> $headers
= dict[]; public function castIntVersion(): int { return (int) $this->getVersion(); } } ϦΫΤετΫϥεͷϝιουΛ ར༻͍ͨ͠ -
src/MessageTrait.php:10:25,34: Could not find method getVersion in an object of
type Acme\MessageTrait (Typing[4053]) src/MessageTrait.php:10:18,22: This is why I think it is an object of type Acme\MessageTrait src/MessageTrait.php:5:7,18: Declaration of Acme\MessageTrait is here ΠϯλʔϑΣʔεʹఆٛ͞Ε͍ͯͳ͍ ϝιουίʔϧෆՄ -
<?hh // strict namespace Acme; trait MessageTrait { require implements
RequestInterface; private dict<string, vec<string>> $headers = dict[]; protected \stdClass $class; public function getStdClass(): \stdClass { return $this->class; } } -
<?hh // strict namespace Acme; trait MessageTrait { require implements
RequestInterface; private dict<string, vec<string>> $headers = dict[]; protected \stdClass $class; public function getStdClass(): \stdClass { return $this->class; } } stdClassΛϓϩύςΟͱͯ͠ѻ͏߹ -
<?hh // strict namespace Acme; class Request implements RequestInterface {
use MessageTrait; protected function getClass(): string { return \strval($this->class); } } Traitʹهड़͞ΕͨϓϩύςΟΛͦͷ·· ར༻͢ΔͱΤϥʔ -
<?hh // strict namespace Acme; class Request implements RequestInterface {
use MessageTrait; public function __construct( protected \stdClass $class ) {} protected function getClass(): string { return \strval($this->class); } } ࣮֬ʹΠϯελϯεΛ͢͜ͱ -
Generic Repository • GenericsͱRepository PatternΛΈ߹Θͤͯɺ ୯Ұͷूʹؔ࿈͚ͮΔ • SpecificationύλʔϯΛΈ߹ΘͤΔ͜ͱͰখ͘͞͠ نଇΛద༻͢Δ •
ଞݴޠͰΑ͘ར༻͞ΕΔύλʔϯ HackͰಉ͜͡ͱ͕Ͱ͖Δʂ -
<?hh // strict namespace Acme\Domain\Model; abstract class Identifier<T> { public
function __construct( private T $id ) {} <<__Rx>> public function id(): T { return $this->id; } <<__Rx>> public function equals(Identifier<T> $id): bool { return $this->id === $id->id(); } } -
<?hh // strict namespace Acme\Domain\Model; abstract class Identifier<T> { public
function __construct( private T $id ) {} <<__Rx>> public function id(): T { return $this->id; } <<__Rx>> public function equals(Identifier<T> $id): bool { return $this->id === $id->id(); } } ҾΓͰར༻͢ΔܕΛҰͭʹ -
<?hh // strict namespace Acme\Domain\Model; abstract class Identifier<T> { public
function __construct( private T $id ) {} <<__Rx>> public function id(): T { return $this->id; } <<__Rx>> public function equals(Identifier<T> $id): bool { return $this->id === $id->id(); } } int int int int -
<?hh // strict namespace Acme\Domain\Model\Article; use namespace Acme\Domain\Model; final class
ArticleId<T> extends Model\Identifier<T> { } -
<?hh // strict namespace Acme\Domain\Model\Article; use namespace Acme\Domain\Model; final class
ArticleId<T> extends Model\Identifier<T> { } ྫ͑ɺIdͱ͍ͬͯ intͱݶΒͳ͍ -
namespace Acme\Domain\Model\Article\Entity; use type DateTime; use type Acme\Domain\Model\EntityInterface; use type
Acme\Domain\Model\Article\ArticleId; use type Acme\Domain\Model\Article\Body; class Article<T> implements EntityInterface<T> { const int EXPIRE_EDIT_TIME = 120; public function __construct( private ArticleId<T> $id, private Body $body, private DateTime $createdAt = new DateTime() ) {} <<__Rx>> public function getID(): T { return $this->id->id(); } // লུ } -
namespace Acme\Domain\Model\Article\Entity; use type DateTime; use type Acme\Domain\Model\EntityInterface; use type
Acme\Domain\Model\Article\ArticleId; use type Acme\Domain\Model\Article\Body; class Article<T> implements EntityInterface<T> { const int EXPIRE_EDIT_TIME = 120; public function __construct( private ArticleId<T> $id, private Body $body, private DateTime $createdAt = new DateTime() ) {} <<__Rx>> public function getID(): T { return $this->id->id(); } // লུ } ୯ҰͷܕͷΈ ޡͬͨܕ͕հೖͮ͠Β͍ (TypecheckerͰݕ) -
interface ArticleRepositoryInterface<TId, T> { public function add(T $entity): void; public
function remove(T $entity): void; public function findById(TId $id): T; public function latestArticles(DateTime $date): Map<TId, public function query( SpecificationInterface<T> $specification ): Map<TId, T>; public function size(): int; } -
interface ArticleRepositoryInterface<TId, T> { public function add(T $entity): void; public
function remove(T $entity): void; public function findById(TId $id): T; public function latestArticles(DateTime $date): Map<TId, public function query( SpecificationInterface<T> $specification ): Map<TId, T>; public function size(): int; } TId : Identifierintಛఆͷܕ͔Ͳ͏͔ɻɻʁ T: EntityͰ͋Δ͕ɺ͜ͷϦϙδτϦͰѻ͏ͷશͯಉ͡ܕ -
abstract class BaseRepository<TId, T as EntityInterface<TId>> implements ArticleRepositoryInterface<TId, T> {
protected Map<TId, T> $collect = Map{}; public function add(T $article): void { $this->collect->add(Pair{$article->getID(), $article}); } // লུ <<__Rx>> public function findById(TId $id): T { if($this->collect->contains($id)) { return $this->collect->at($id); } throw new \RuntimeException('Not Found.'); } } -
abstract class BaseRepository<TId, T as EntityInterface<TId>> implements ArticleRepositoryInterface<TId, T> {
protected Map<TId, T> $collect = Map{}; public function add(T $article): void { $this->collect->add(Pair{$article->getID(), $article}); } // লུ <<__Rx>> public function findById(TId $id): T { if($this->collect->contains($id)) { return $this->collect->at($id); } throw new \RuntimeException('Not Found.'); } } TId : Identifierintಛఆͷܕ͔Ͳ͏͔ɻɻʁ T: EntityInterfaceΛ࣮ͯ͠Δ͕ɺTIdࢦఆ͞Εͨͷ -
abstract class BaseRepository<TId, T as EntityInterface<TId>> implements ArticleRepositoryInterface<TId, T> {
protected Map<TId, T> $collect = Map{}; public function add(T $article): void { $this->collect->add(Pair{$article->getID(), $article}); } // লུ <<__Rx>> public function findById(TId $id): T { if($this->collect->contains($id)) { return $this->collect->at($id); } throw new \RuntimeException('Not Found.'); } } ίϨΫγϣϯɺ<TId, T> ͷϚοϓʹ Ұ؏ੑ͕͋Γɺ͜ΕҎ֎ͷͷར༻͞Εͳ͍ -
<?hh // strict namespace Acme\Infrastructure\Persistence\Map; use type DateTime; use type
Acme\Domain\Model\Article\Entity\Article; class ArticleRepository extends BaseRepository<int, Article<int>> { <<__Rx>> public function latestArticles( DateTime $date ): Map<int, Article<int>> { return $this->collect->filter( $v ==> $v->createdAt() > $date ); } } -
<?hh // strict namespace Acme\Infrastructure\Persistence\Map; use type DateTime; use type
Acme\Domain\Model\Article\Entity\Article; class ArticleRepository extends BaseRepository<int, Article<int>> { <<__Rx>> public function latestArticles( DateTime $date ): Map<int, Article<int>> { return $this->collect->filter( $v ==> $v->createdAt() > $date ); } } ͲΜͳܕΛར༻͢Δͷ͔ɺ۩ΫϥεͰ໌ه -
<?hh // strict namespace Acme\Infrastructure\Persistence\Map; use type DateTime; use type
Acme\Domain\Model\Article\Entity\Article; class ArticleRepository extends BaseRepository<int, Article<int>> { <<__Rx>> public function latestArticles( DateTime $date ): Map<int, Article<int>> { return $this->collect->filter( $v ==> $v->createdAt() > $date ); } } ಛఆͷूݶఆͷॲཧͳͲ͕͋Εɺ ΠϯλʔϑΣʔεՃɺઐ༻ͷॲཧͷΈهड़ -
<?hh // strict namespace Acme\Infrastructure\Persistence\Map; use type Acme\Domain\Model\Bookmark\Entity\Bookmark; class BookmarkRepository
extends BaseRepository<string, Bookmark<string>> { } ྫ͑ར༻͢Δܕ͚ͩΛม͑Δ ूͷૢ࡞ͱͯ͜͠Ε͚ͩͰ݁ ৄࡉͳॲཧ༷ύλʔϯͳͲʹ -
<?hh // strict namespace Acme\Domain\Model\Article\Specification; interface SpecificationInterface<T> { <<__Rx>> public
function isSatisfiedBy(T $entity): bool; } ༷Λຬͨ͢ͷ͔Ͳ͏͔ -
class LatestPostSpecification implements SpecificationInterface<Article<int>> { public function __construct( private DateTime
$since ) {} <<__Rx>> public function isSatisfiedBy( Article<int> $article ): bool { return $article->createdAt() > $this->since; } } ͜Ε·Ͱͷྫͱಉ༷ʹ۩Ϋϥεʹ ࣮ࡍʹద༻ͤ͞ΔܕΛهड़ -
class LatestPostSpecification implements SpecificationInterface<Article<int>> { public function __construct( private DateTime
$since ) {} <<__Rx>> public function isSatisfiedBy( Article<int> $article ): bool { return $article->createdAt() > $this->since; } } ࢦఆ͞Εͨ࣌ΑΓ৽͍͠هࣄͳΒ ༷͕ຬͨ͞Ε·͢Α -
<<__Rx>> public function query( SpecificationInterface<T> $specification ): Map<TId, T> {
return $this->collect->filter( $v ==> $specification->isSatisfiedBy($v) ); } ༷ɾϦϙδτϦͱΈ߹ΘͤΔ -
use type Vendor\Path\ArticleRepositoryInterface as Repository; use type Vendor\Path\\ArticleSpecificationFactoryInterface as SpecificationFactory;
final class LatestArticleFeed { public function __construct( private Repository<int, Article<int>> $repository, private SpecificationFactory<Article<int>> $specification ) { } ࢦఆͨ͠ܕΛར༻͢ΔΑ͏ʹద༻͞Εͨ ΠϯλʔϑΣʔεΛ࣮ͨ͠ͷΛར༻͍ͯͩ͘͠͞ -
public function execute( FeedRequestTransfer $request ): vec<shape( 'id' => int,
'content' => string, 'created_at' => \DateTime)> { $result = $this->repository->query( $this->specificationFactory ->createLatestPosts($request->getDateTime() )); if(C\count($result)) { return Vec\map($result, ($v) ==> { return shape( 'id' => $v->getID(), 'content' => $v->body()->content(), 'created_at' => $v->createdAt() ); }); } return vec[]; } ༷Λຬͨ͢هࣄΦϒδΣΫτΛϦϙδτϦ͔Βऔಘ -
public function execute( FeedRequestTransfer $request ): vec<shape( 'id' => int,
'content' => string, 'created_at' => \DateTime)> { $result = $this->repository->query( $this->specificationFactory ->createLatestPosts($request->getDateTime() )); if(C\count($result)) { return Vec\map($result, ($v) ==> { return shape( 'id' => $v->getID(), 'content' => $v->body()->content(), 'created_at' => $v->createdAt() ); }); } return vec[]; } Collectionૢ࡞ ϦϙδτϦ͔Βऔಘ͞ΕͨΦϒδΣΫτΛҰׅૢ࡞ *͜͜ͰshapeͷΈͷvecྻʹ -
ܕએݴ͞ΕͨΠϯλʔϑΣʔεΛຬͨ͢ ۩ΫϥεͷΠϯελϯε $service = new Application\Service\LatestArticleFeed( new Map\ArticleRepository(), new Map\ArticleSpecificationFactory()
); $result = $service->execute( new Application\FeedRequestTransfer([ 'datetime' => new DateTime('-4 hours'), ]) ); -
$service = new Application\Service\LatestArticleFeed( new Map\ArticleRepository(), new Map\ArticleSpecificationFactory() ); $result
= $service->execute( new Application\FeedRequestTransfer([ 'datetime' => new DateTime('-4 hours'), ]) ); ϑΥʔϜAPIͳͲ͔ΒΛૹ৴ -
final class FeedRequestTransfer { const type FeedRequest = shape( 'datetime'
=> DateTime ); public function __construct( private array<arraykey, mixed> $request ) {} public function getDateTime(): DateTime { $request = $this->request as this::FeedRequest; return $request['datetime']; } } ҰൠతͳྻΛड͚औΔ -
final class FeedRequestTransfer { const type FeedRequest = shape( 'datetime'
=> DateTime ); public function __construct( private array<arraykey, mixed> $request ) {} public function getDateTime(): DateTime { $request = $this->request as this::FeedRequest; return $request['datetime']; } } ShapeͰྻʹରͯ͠ ظ͢ΔϑΟʔϧυͱܕఆٛ -
final class FeedRequestTransfer { const type FeedRequest = shape( 'datetime'
=> DateTime ); public function __construct( private array<arraykey, mixed> $request ) {} public function getDateTime(): DateTime { $request = $this->request as this::FeedRequest; return $request['datetime']; } } ϑΟʔϧυͱܕݕࠪ OKͳΒͦͷ··ྻ NGͳΒType Error͕εϩʔ