假设我有一个 Rectangle 类。要使用它,我会这样做:
$rectangle = new Rectangle( 100, 50, new Color('#ff0000') );
然而,由于这将是一个公共(public) API,我想为最终用户尽可能地简化它。最好它只接受十六进制字符串:
$rectangle = new Rectangle( 100, 50, '#ff0000');
现在的问题是我需要在 Rectangle 类中实例化 Color 对象
class Rectangle {
protected $width;
protected $height;
protected $fillColor;
function __construct( $width, $height, $fillColor ){
$this->width = $width;
$this->height = $height;
$this->fillColor = new Color( $fillColor );
}
}
学习了依赖注入(inject),这被认为是不好的。或者是吗?什么是最好的方法?
最佳答案
我会使用一个工厂类,它接受一个(可能)参数数组并返回准备好的实例化 Rectangle 对象。根据您的设计和 API 规范,有多种可能性可以做到这一点。
class MyAPIFactory
{
public function createRectangle($params)
{
// do some checks of the params
$color = new Color($params['color']);
Rectangle = new Rectangle($params['width'], $params['height'], $color);
return $color;
}
}
此外,根据您的需要和设计,您可以选择工厂方法
或抽象工厂
。假设您有一个 interface GeometricalShape
和 class Rectangle implements GeometricalShape
以及 class Circle implements GeometricalShape
首先您可以使用类似
class MyApiFactory
{
public static function createRectangle(array $params) { /*...*/ }
public static function createCircle(array $params) { /*...*/ }
}
或
abstract class ShapeFactory
{
/**
* @return GeometricalShape
*/
abstract public function createInstance(array $params);
abstract protected function checkParams(array &$params);
}
class RectangleFactory extends ShapeFactory
{
public function createInstance(array $params)
{
// ...
}
protected function checkParams(array &$params)
{
if(empty($params['width'])) {
throw new Exception('Missing width');
}
if (empty($params['height'])) {
throw new Exception('Missing height');
}
// you could even make color optional
if (empty($params['color'])) {
$params['color'] = Color::DEFAULT_COLOR;
}
}
}
关于php - 如何在不牺牲依赖注入(inject)的情况下简化 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31779468/