|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Created by PhpStorm. |
| 4 | + * User: Inhere |
| 5 | + * Date: 2015/2/7 |
| 6 | + * Time: 19:14 |
| 7 | + * Use : |
| 8 | + * File: TraitUseOption.php |
| 9 | + */ |
| 10 | + |
| 11 | +namespace inhere\librarys\traits; |
| 12 | + |
| 13 | +/** |
| 14 | + * Class TraitUseSimpleOption |
| 15 | + * @package inhere\librarys\traits |
| 16 | + * |
| 17 | + * @property array $options 必须在使用的类定义此属性, 在 Trait 中已定义的属性,在使用 Trait 的类中不能再次定义 |
| 18 | + */ |
| 19 | +trait TraitUseSimpleOption |
| 20 | +{ |
| 21 | + /** |
| 22 | + * 在 Trait 中已定义的属性,在使用 Trait 的类中不能再次定义 |
| 23 | + * 而已定义的方法 可以被覆盖,但无法直接使用 已定义的方法体 e.g. parent::set(...) |
| 24 | + * 只能完全重写。但可以用继承 使用了 Trait 的父级来解决,具体请看 \inhere\librarys\dataStorage\example 的 例子 |
| 25 | + */ |
| 26 | + //protected $options; |
| 27 | + |
| 28 | + /** |
| 29 | + * @param $name |
| 30 | + * @return bool |
| 31 | + */ |
| 32 | + public function hasOption($name) |
| 33 | + { |
| 34 | + return array_key_exists($name, $this->options); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Method to get property Options |
| 39 | + * @param string $name |
| 40 | + * @param mixed $default |
| 41 | + * @return mixed |
| 42 | + */ |
| 43 | + public function getOption($name, $default = null) |
| 44 | + { |
| 45 | + if (array_key_exists($name, $this->options)) { |
| 46 | + $value = $this->options[$name]; |
| 47 | + } else { |
| 48 | + $value = $default; |
| 49 | + } |
| 50 | + |
| 51 | + if ($value && is_callable($value) && ($value instanceof \Closure)) { |
| 52 | + $value = $value(); |
| 53 | + } |
| 54 | + |
| 55 | + return $value; |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Method to set property options |
| 60 | + * @param string $name |
| 61 | + * @param mixed $value |
| 62 | + * @return static Return self to support chaining. |
| 63 | + */ |
| 64 | + public function setOption($name, $value) |
| 65 | + { |
| 66 | + $this->options[$name] = $value; |
| 67 | + |
| 68 | + return $this; |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Method to get property Options |
| 73 | + * @return array |
| 74 | + */ |
| 75 | + public function getOptions() |
| 76 | + { |
| 77 | + return $this->options; |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * Method to set property options |
| 82 | + * @param array $options |
| 83 | + * @param bool $merge |
| 84 | + * @return static Return self to support chaining. |
| 85 | + */ |
| 86 | + public function setOptions($options, $merge = false) |
| 87 | + { |
| 88 | + if ( $merge ) { |
| 89 | + $this->options = array_merge($this->options, $options); |
| 90 | + } else { |
| 91 | + $this->options = $options; |
| 92 | + } |
| 93 | + |
| 94 | + return $this; |
| 95 | + } |
| 96 | +} |
0 commit comments