1 回答

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
你完全遠(yuǎn)離()。如何在代碼中完全看不到工作。沒(méi)關(guān)系,你有他們負(fù)責(zé)不同工作的課程??赡苁腔蛭也?,它們是通過(guò)尊重來(lái)實(shí)現(xiàn)的。除了假設(shè)之外,SRP 在代碼中的可見(jiàn)性要低得多。SRPSingle Responsibility PrincipleSRPSRP
在 中,類依賴于其他類。這是完全正常的。 在您的代碼中完全可見(jiàn)。但是你不能像構(gòu)建復(fù)雜結(jié)構(gòu)時(shí)那樣通過(guò)構(gòu)造函數(shù)方法來(lái)維護(hù)。這應(yīng)該是以下方式的一些內(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í)行此操作,您需要使用 。 實(shí)際創(chuàng)建其他對(duì)象。假設(shè)您有一個(gè)工廠方法模式實(shí)現(xiàn),并且該實(shí)現(xiàn)將負(fù)責(zé)創(chuàng)建具有依賴項(xiàng)的對(duì)象。假設(shè)您在以下代碼段中導(dǎo)入了所需的所有類: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);
哦!我有一個(gè)寫(xiě)在媒體上.如果你可以讀它。這是戰(zhàn)略調(diào)整計(jì)劃的鏈接SRP
希望這會(huì)幫助你!祝您編碼愉快!
- 1 回答
- 0 關(guān)注
- 148 瀏覽
添加回答
舉報(bào)