实施策略模式

通常情况下,运行时条件会迫使开发人员定义做同一件事的几种方法。传统上,这涉及到大量的if/elseif/else命令块。然后,你将不得不在if语句中定义大量的逻辑块,或者创建一系列函数或方法来实现不同的方法。策略模式试图将这一过程正式化,让主类封装了一系列子类,这些子类代表了解决同一问题的不同方法。

如何做…

1.在这个例子中,我们将使用前面定义的GetSet hydrator类作为策略。我们将定义一个主Application\Generic\Hydrator\Any类,然后它将消耗Application\Generic\Hydrator\Strategy命名空间中的策略类,包括GetSetPublicPropsExtending

2.我们首先定义类常量,以反映可用的内置策略。

  1. namespace Application\Generic\Hydrator;
  2. use InvalidArgumentException;
  3. use Application\Generic\Hydrator\Strategy\ {
  4. GetSet, PublicProps, Extending };
  5. class Any
  6. {
  7. const STRATEGY_PUBLIC = 'PublicProps';
  8. const STRATEGY_GET_SET = 'GetSet';
  9. const STRATEGY_EXTEND = 'Extending';
  10. protected $strategies;
  11. public $chosen;

3.然后我们定义一个构造函数,将所有内置策略添加到$strategies属性中。

  1. public function __construct()
  2. {
  3. $this->strategies[self::STRATEGY_GET_SET] = new GetSet();
  4. $this->strategies[self::STRATEGY_PUBLIC] = new PublicProps();
  5. $this->strategies[self::STRATEGY_EXTEND] = new Extending();
  6. }

4.我们还添加了一个addStrategy()方法,使我们可以覆盖或添加新的策略,而无需重新编写类。

  1. public function addStrategy($key, HydratorInterface $strategy)
  2. {
  3. $this->strategies[$key] = $strategy;
  4. }

5.hydrate()extract()方法只是简单地调用了所选策略的方法。

  1. public function hydrate(array $array, $object)
  2. {
  3. $strategy = $this->chooseStrategy($object);
  4. $this->chosen = get_class($strategy);
  5. return $strategy::hydrate($array, $object);
  6. }
  7. public function extract($object)
  8. {
  9. $strategy = $this->chooseStrategy($object);
  10. $this->chosen = get_class($strategy);
  11. return $strategy::extract($object);
  12. }

6.棘手的是要弄清楚选择哪种策略。为此我们定义了 chooseStrategy(),它以一个对象作为参数。我们首先通过获取一个类方法的列表来执行一些检测工作。然后我们扫描列表,看看是否有getXXX()setXXX()方法。如果有,我们就选择GetSet hydrator作为我们选择的策略。

  1. public function chooseStrategy($object)
  2. {
  3. $strategy = NULL;
  4. $methodList = get_class_methods(get_class($object));
  5. if (!empty($methodList) && is_array($methodList)) {
  6. $getSet = FALSE;
  7. foreach ($methodList as $method) {
  8. if (preg_match('/^get|set.*$/i', $method)) {
  9. $strategy = $this->strategies[self::STRATEGY_GET_SET];
  10. break;
  11. }
  12. }
  13. }

7.还是在我们的 chooseStrategy()方法中,如果没有getter或setter,我们接下来使用get_class_vars()来确定是否有任何可用的属性。如果有的话,我们选择PublicProps作为我们的转化器。

  1. if (!$strategy) {
  2. $vars = get_class_vars(get_class($object));
  3. if (!empty($vars) && count($vars)) {
  4. $strategy = $this->strategies[self::STRATEGY_PUBLIC];
  5. }
  6. }

8.如果所有其他方法都失败了,我们又回到了Extending hydrator,它返回一个新的类,简单地扩展对象类,从而使任何公共或保护的属性可用。

  1. if (!$strategy) {
  2. $strategy = $this->strategies[self::STRATEGY_EXTEND];
  3. }
  4. return $strategy;
  5. }
  6. }

9.现在我们将注意力转向策略本身。首先,我们定义一个新的Application\Generic\Hydrator\Strategy命名空间。

10.在新的命名空间中,我们定义了一个接口,允许我们识别任何可以被Application\Generic\Hydrator\Any消耗的策略。

  1. namespace Application\Generic\Hydrator\Strategy;
  2. interface HydratorInterface
  3. {
  4. public static function hydrate(array $array, $object);
  5. public static function extract($object);
  6. }
  1. GetSet转化器与前面两个配方中定义的完全一样,唯一增加的是它将实现新的接口。
  1. namespace Application\Generic\Hydrator\Strategy;
  2. class GetSet implements HydratorInterface
  3. {
  4. public static function hydrate(array $array, $object)
  5. {
  6. // defined in the recipe:
  7. // "Creating an Array to Object Hydrator"
  8. }
  9. public static function extract($object)
  10. {
  11. // defined in the recipe:
  12. // "Building an Object to Array Hydrator"
  13. }
  14. }
  1. 下一个hydrator只是简单地读写公共属性。
  1. namespace Application\Generic\Hydrator\Strategy;
  2. class PublicProps implements HydratorInterface
  3. {
  4. public static function hydrate(array $array, $object)
  5. {
  6. $propertyList= array_keys(
  7. get_class_vars(get_class($object)));
  8. foreach ($propertyList as $property) {
  9. $object->$property = $array[$property] ?? NULL;
  10. }
  11. return $object;
  12. }
  13. public static function extract($object)
  14. {
  15. $array = array();
  16. $propertyList = array_keys(
  17. get_class_vars(get_class($object)));
  18. foreach ($propertyList as $property) {
  19. $array[$property] = $object->$property;
  20. }
  21. return $array;
  22. }
  23. }
  1. 最后,水兵的瑞士军刀—Extending,扩展了对象类,从而提供了对属性的直接访问。我们进一步定义了神奇的getter和setter来提供对属性的访问。

14.hydrate()方法是最困难的,因为我们假设没有定义getter或setter,也没有定义可见性级别为public的属性。相应地,我们需要定义一个类,该类扩展了要被转化的对象的类。我们的做法是首先定义一个字符串,这个字符串将被用作构建新类的模板。

  1. namespace Application\Generic\Hydrator\Strategy;
  2. class Extending implements HydratorInterface
  3. {
  4. const UNDEFINED_PREFIX = 'undefined';
  5. const TEMP_PREFIX = 'TEMP_';
  6. const ERROR_EVAL = 'ERROR: unable to evaluate object';
  7. public static function hydrate(array $array, $object)
  8. {
  9. $className = get_class($object);
  10. $components = explode('\\', $className);
  11. $realClass = array_pop($components);
  12. $nameSpace = implode('\\', $components);
  13. $tempClass = $realClass . self::TEMP_SUFFIX;
  14. $template = 'namespace '
  15. . $nameSpace . '{'
  16. . 'class ' . $tempClass
  17. . ' extends ' . $realClass . ' '

15.继续使用hydrate()方法,我们定义了一个$values属性和一个构造函数,该构造函数将要转化的数组作为参数分配到对象中。我们在值的数组中循环,将值分配给属性。我们还定义了一个有用的 getArrayCopy() 方法,在需要时返回这些值,以及一个神奇的 __get() 方法来模拟直接属性访问。

  1. . '{ '
  2. . ' protected $values; '
  3. . ' public function __construct($array) '
  4. . ' { $this->values = $array; '
  5. . ' foreach ($array as $key => $value) '
  6. . ' $this->$key = $value; '
  7. . ' } '
  8. . ' public function getArrayCopy() '
  9. . ' { return $this->values; } '

16.为了方便起见,我们定义了一个神奇的 __get() 方法,它可以模拟直接访问变量,就像它们是公共的一样。

  1. . ' public function __get($key) '
  2. . ' { return $this->values[$key] ?? NULL; } '

17.还是在新类的模板中,我们还定义了一个神奇的__call()方法,它可以模拟getters和setters。

  1. . ' public function __call($method, $params) '
  2. . ' { '
  3. . ' preg_match("/^(get|set)(.*?)$/i", '
  4. . ' $method, $matches); '
  5. . ' $prefix = $matches[1] ?? ""; '
  6. . ' $key = $matches[2] ?? ""; '
  7. . ' $key = strtolower(substr($key, 0, 1)) '
  8. . ' substr($key, 1); '
  9. . ' if ($prefix == "get") { '
  10. . ' return $this->values[$key] ?? NULL; '
  11. . ' } else { '
  12. . ' $this->values[$key] = $params[0]; '
  13. . ' } '
  14. . ' } '
  15. . '} '
  16. . '} // ends namespace ' . PHP_EOL
  1. 最后,还是在新类的模板中,我们在全局命名空间中添加一个函数,用于构建和返回类实例。
  1. . 'namespace { '
  2. . 'function build($array) '
  3. . '{ return new ' . $nameSpace . '\\'
  4. . $tempClass . '($array); } '
  5. . '} // ends global namespace '
  6. . PHP_EOL;
  1. 还是在hydrate()方法中,我们使用eval()执行完成的模板。然后我们运行刚刚在模板最后定义的build()方法。注意,由于我们不确定要填充的类的命名空间,我们从全局命名空间定义并调用build()
  1. try {
  2. eval($template);
  3. } catch (ParseError $e) {
  4. error_log(__METHOD__ . ':' . $e->getMessage());
  5. throw new Exception(self::ERROR_EVAL);
  6. }
  7. return \build($array);
  8. }
  1. extract()方法更容易定义,因为我们的选择极其有限。使用神奇的方法扩展一个类并从一个数组中填充它是很容易实现的。反之则不然。如果我们要扩展这个类,我们将失去所有的属性值,因为我们是在扩展这个类,而不是对象实例。相应地,我们唯一的选择是使用获取器和公共属性的组合。
  1. public static function extract($object)
  2. {
  3. $array = array();
  4. $class = get_class($object);
  5. $methodList = get_class_methods($class);
  6. foreach ($methodList as $method) {
  7. preg_match('/^(get)(.*?)$/i', $method, $matches);
  8. $prefix = $matches[1] ?? '';
  9. $key = $matches[2] ?? '';
  10. $key = strtolower(substr($key, 0, 1))
  11. . substr($key, 1);
  12. if ($prefix == 'get') {
  13. $array[$key] = $object->$method();
  14. }
  15. }
  16. $propertyList= array_keys(get_class_vars($class));
  17. foreach ($propertyList as $property) {
  18. $array[$property] = $object->$property;
  19. }
  20. return $array;
  21. }
  22. }

如何运行…

你可以先定义三个具有相同属性的测试类:firstNamelastName,等等。第一个类,Person,应该有受保护的属性以及getters和setters。第二个,PublicPerson,将有公共属性。第三个,ProtectedPerson,有受保护的属性,但没有getters和setters

  1. <?php
  2. namespace Application\Entity;
  3. class Person
  4. {
  5. protected $firstName = '';
  6. protected $lastName = '';
  7. protected $address = '';
  8. protected $city = '';
  9. protected $stateProv = '';
  10. protected $postalCode = '';
  11. protected $country = '';
  12. public function getFirstName()
  13. {
  14. return $this->firstName;
  15. }
  16. public function setFirstName($firstName)
  17. {
  18. $this->firstName = $firstName;
  19. }
  20. // be sure to define remaining getters and setters
  21. }
  22. <?php
  23. namespace Application\Entity;
  24. class PublicPerson
  25. {
  26. private $id = NULL;
  27. public $firstName = '';
  28. public $lastName = '';
  29. public $address = '';
  30. public $city = '';
  31. public $stateProv = '';
  32. public $postalCode = '';
  33. public $country = '';
  34. }
  35. <?php
  36. namespace Application\Entity;
  37. class ProtectedPerson
  38. {
  39. private $id = NULL;
  40. protected $firstName = '';
  41. protected $lastName = '';
  42. protected $address = '';
  43. protected $city = '';
  44. protected $stateProv = '';
  45. protected $postalCode = '';
  46. protected $country = '';
  47. }

现在你可以定义一个名为chap_11_strategy_pattern.php的调用程序,它可以设置自动加载并使用相应的类。

  1. <?php
  2. require __DIR__ . '/../Application/Autoload/Loader.php';
  3. Application\Autoload\Loader::init(__DIR__ . '/..');
  4. use Application\Entity\ { Person, PublicPerson, ProtectedPerson };
  5. use Application\Generic\Hydrator\Any;
  6. use Application\Generic\Hydrator\Strategy\ { GetSet, Extending, PublicProps };

接下来,创建一个Person的实例,并运行setters来定义属性的值。

  1. $obj = new Person();
  2. $obj->setFirstName('Li\'lAbner');
  3. $obj->setLastName('Yokum');
  4. $obj->setAddress('1 Dirt Street');
  5. $obj->setCity('Dogpatch');
  6. $obj->setStateProv('Kentucky');
  7. $obj->setPostalCode('12345');
  8. $obj->setCountry('USA');

接下来,创建一个Any hydrator的实例,调用extract(),并使用var_dump()来查看结果。

  1. $hydrator = new Any();
  2. $b = $hydrator->extract($obj);
  3. echo "\nChosen Strategy: " . $hydrator->chosen . "\n";
  4. var_dump($b);

从下面的输出中观察,选择了GetSet策略。

实施策略模式 - 图1

{% hint style=”info” %} 请注意,由于其可见性级别是私有的,所以没有设置id属性。 {% endhint %}

接下来,你可以定义一个具有相同值的数组。在Any实例上调用hydrate(),并提供一个新的PublicPerson实例作为参数。

  1. $a = [
  2. 'firstName' => 'Li\'lAbner',
  3. 'lastName' => 'Yokum',
  4. 'address' => '1 Dirt Street',
  5. 'city' => 'Dogpatch',
  6. 'stateProv' => 'Kentucky',
  7. 'postalCode' => '12345',
  8. 'country' => 'USA'
  9. ];
  10. $p = $hydrator->hydrate($a, new PublicPerson());
  11. echo "\nChosen Strategy: " . $hydrator->chosen . "\n";
  12. var_dump($p);

这就是结果。请注意,在这种情况下选择了PublicProps策略。

实施策略模式 - 图2

最后,再次调用hydrate(),但这次提供一个ProtectedPerson的实例作为对象参数。然后我们调用getFirstName()getLastName()来测试神奇的获取器。我们还将名字和姓氏作为直接变量访问。

  1. $q = $hydrator->hydrate($a, new ProtectedPerson());
  2. echo "\nChosen Strategy: " . $hydrator->chosen . "\n";
  3. echo "Name: {$q->getFirstName()} {$q->getLastName()}\n";
  4. echo "Name: {$q->firstName} {$q->lastName}\n";
  5. var_dump($q);

这是最后的输出,显示选择了Extending策略。你还会注意到,这个实例是一个新的ProtectedPerson_TEMP类,而且受保护的属性已经被完全填充。

实施策略模式 - 图3