如果你想實(shí)現(xiàn)多態(tài)方法,最好創(chuàng)建存儲(chǔ)庫或僅用于管理該邏輯的東西。
這是示例。
class SampleRepository { /** * repository instance value * * @var string[] | null */ private $sampleArray; // maybe here is SEASON or EXPIRY or null /** * constructor * * @param string[] | null $sampleArray */ public function __construct($sampleArray) { $this->sampleArray = $sampleArray; } /** * execute like class interface role * * @return array */ public function execute() { return (!$this->sampleArray) ? [] : $this->getResult(); } /** * get result * * @return array */ private function getResult() { // maybe pattern will be better to manage another class or trait. $pattern = [ "SEASON" => new Season(), "EXPIRY" => new Expiry() ]; return collect($this->sampleArray)->map(function($itemKey){ $requestClass = data_get($pattern,$itemKey); if (!$requestClass){ // here is space you don't expect class or canIt find correct class return ["something wrong"]; } return $requestClass->execute(); })->flatten(); } }
你可以這樣調(diào)用。
$sampleRepository = new SampleRepository($sampleValue); // expect string[] or null like ["SEASON"],["SEASON","EXPIRY"],null $result = $sampleRepository->execute(); // [string] or [string,string] or []
此方法僅適用于您的參數(shù)指定值。 如果Season類和Expiry類的返回結(jié)果幾乎相同,那么最好在trait上進(jìn)行管理。 (即示例代碼中的 $pattern)
嘗試一些。
我讀了評論,所以關(guān)注..
例如,它更愿意只獲取 getResult() 的結(jié)果。 因此,某些模式和如此多的邏輯不應(yīng)該寫在 getResult() 上;
如果您使用特征,這是示例。 首先,您需要?jiǎng)?chuàng)建管理行為類。
行為.php
<?php namespace App\Repositories; class Behavior { use Behavior\BehaviorTrait; // if you need to add another pattern, you can add trait here. }
然后,您需要在同級位置創(chuàng)建Behavior目錄。 你移動(dòng)該目錄,你就創(chuàng)建了這樣的特征文件。
<?php namespace App\Repositories\Behavior; trait BehaviorTrait { public static function findAccessibleClass(string $itemKey) { return data_get([ "SEASON" => new Season(), "EXPIRY" => new Expiry() ],$itemKey); } }
findAccessibleClass() 方法負(fù)責(zé)查找正確的類。
然后,你可以像這樣調(diào)用這個(gè)方法。
private function getResult() { return collect($this->sampleArray)->map(function($itemKey){ $requestClass = Behavior::findAccessibleClass($itemKey); // fix here. if (!$requestClass){ // here is space you don't expect class or canIt find correct class return ["something wrong"]; } return $requestClass->execute(); })->flatten(); }
如果 getResult() 中的代碼太多,最好將負(fù)責(zé)的代碼分開。
要?jiǎng)?chuàng)建Behavior Trait,getResult不需要負(fù)責(zé)行為邏輯。簡而言之,它將很容易測試或修復(fù)。
希望一切順利。