1 回答

TA貢獻1863條經(jīng)驗 獲得超2個贊
你完全遠離()。如何在代碼中完全看不到工作。沒關系,你有他們負責不同工作的課程??赡苁腔蛭也拢鼈兪峭ㄟ^尊重來實現(xiàn)的。除了假設之外,SRP 在代碼中的可見性要低得多。SRPSingle Responsibility PrincipleSRPSRP
在 中,類依賴于其他類。這是完全正常的。 在您的代碼中完全可見。但是你不能像構(gòu)建復雜結(jié)構(gòu)時那樣通過構(gòu)造函數(shù)方法來維護。這應該是以下方式的一些內(nèi)容:OOPDependency InjectionDependency Injection
<?php
// given string is not empty
$nonEmptyString = new NonEmptyString('/tmp/xyzk7kjnbrukhg');
// validates for string to be a path
$path = new Path($nonEmptyString);
// validates given string is a valid file path
$filePath = new FilePath($path);
// validates given file is uploaded file
$uploadedFile = new UploadedFile($filePath);
// checks given item is a readable file / permissions check
$readableFile = new ReadableFile($uploadedFile);
// makes sure given file is an image file
$imageFile = new ImageFile($readableFile);
// holds all rules for product image only
$productImage = new ProductImage($imageFile);
但這也不是正確的方法。要以正確的方式執(zhí)行此操作,您需要使用 。 實際創(chuàng)建其他對象。假設您有一個工廠方法模式實現(xiàn),并且該實現(xiàn)將負責創(chuàng)建具有依賴項的對象。假設您在以下代碼段中導入了所需的所有類:Factory Method Design PatternFactory Method Design PatternImageFileProductImageImageFile
<?php
class ImageFileFactory implements FactoryInterface
{
public static function make($string)
{
// given string is not empty
$nonEmptyString = new NonEmptyString($string);
// validates for string to be a path
$path = new Path($nonEmptyString);
// validates given string is a valid file path
$filePath = new FilePath($path);
// validates given file is uploaded file
$uploadedFile = new UploadedFile($filePath);
// checks given item is a readable file / permissions check
$readableFile = new ReadableFile($uploadedFile);
// makes sure given file is an image file
return new ImageFile($readableFile);
}
}
// Creates ImageFile instance
$imageFile = ImageFileFactory::make('/tmp/xyzk7kjnbrukhg');
// holds all rules for product image only
$productImage = new ProductImage($imageFile);
哦!我有一個寫在媒體上.如果你可以讀它。這是戰(zhàn)略調(diào)整計劃的鏈接SRP
希望這會幫助你!祝您編碼愉快!
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報