php - How to simplify an API without sacrificing Dependency Injection? -


let's have rectangle class. use i'd do:

$rectangle = new rectangle( 100, 50, new color('#ff0000') ); 

however public api, want simplify end-users as possible. preferably accept hex string:

$rectangle = new rectangle( 100, 50, '#ff0000'); 

the problem need instantiate color object inside rectangle class

class rectangle {      protected $width;     protected $height;     protected $fillcolor;      function __construct( $width, $height, $fillcolor ){         $this->width = $width;         $this->height = $height;         $this->fillcolor = new color( $fillcolor );     } } 

having learned dependency injection considered bad. or it? what's best approach?

i use factory class, accepts array (possibly) of arguments , returns ready instantiated rectangle object. there many possibilities how that, depending on design , api specification.

class myapifactory {     public function createrectangle($params)     {         // checks of params         $color = new color($params['color']);         rectangle = new rectangle($params['width'], $params['height'], $color);         return $color;     } } 

further depending on needs , design can choose between factory method or abstract factory. have interface geometricalshape , class rectangle implements geometricalshape class circle implements geometricalshape first use

class myapifactory {     public static function createrectangle(array $params) { /*...*/ }     public static function createcircle(array $params) { /*...*/ } } 

or

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');         }         // make color optional         if (empty($params['color'])) {             $params['color'] = color::default_color;         }      } } 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -