虽然试图坚持单一责任规则,但我的类开始看起来像这样
$productImage = new ProductImage(// holds all rules for product image only
new ImageFile( // makes sure given file is an image file
new ReadableFile( // checks given item is a readable file / permissions check
new UploadedFile( // validates given file is uploaded file
new FilePath( // validates given string is a valid file path
new Path( // validates for string to be a path
new NonEmptyString( // given string is not empty
'/tmp/xyzk7kjnbrukhg'
)
)
)
)
)
)
);
这只是一个示例。 从表面上看,它看起来很酷,因为它提供了非常简单和可测试的类。但正如你注意到的那样,代码的可读性或可用性很糟糕。我甚至需要编写无数行代码来处理上传文件的简单初始化(如上面的代码所示(。
我开始觉得有些不对劲,我误解了单一责任原则的概念。
是如何处理每个类的单一责任的纯 OOP,还是我偏离了目标?
你完全远离SRP
(Single Responsibility Principle
(。SRP
的工作方式在您的代码中完全看不到。没关系,你有他们负责不同工作的班级。可能是或者我猜,它们是通过尊重SRP
来实现的.除了假设之外,SRP 在您的代码中的可见性要低得多。
在OOP
,类依赖于其他类。这是完全正常的。Dependency Injection
完全体现在您的代码中。但是,您无法像构建复杂结构时那样通过构造函数方法来维护Dependency 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);
但这也不是正确的做法。要以正确的方式执行此操作,您需要使用Factory Method Design Pattern
.Factory Method Design Pattern
实际上会创建其他对象。假设您有一个工厂方法模式实现,并且它将负责创建ImageFile
对象,因为ProductImage
具有ImageFile
依赖项。假设您在以下代码片段中导入了所需的所有类:
<?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);
哦!我在SRP
上有一篇关于介质的文章.如果你能读到它。这是SRP的链接
希望这对您有所帮助!祝您编码愉快!