From 99f360d3212353b2a4bc59f5c27fa4841e1fa576 Mon Sep 17 00:00:00 2001 From: LIERLIER <1113093541@qq.com> Date: Fri, 18 Aug 2023 16:33:27 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8A=8A=E5=AD=97=E6=AE=B5=E7=A7=BB=E8=BF=9BBe?= =?UTF-8?q?havior?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- readme.md | 72 +++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 57 insertions(+), 15 deletions(-) diff --git a/readme.md b/readme.md index 0134862..087e475 100644 --- a/readme.md +++ b/readme.md @@ -24,6 +24,28 @@ class BitFlagBehavior extends Behavior * @var array[] $bitFlags 位标志映射表 */ public $bitFlags = []; + /** + * @var array + */ + private $_attributes = []; + + /** + * {@inheritdoc} + */ + public function init() + { + parent::init(); + $this->initAttributes(); + } + + /** + * 初始化属性数组 + */ + private function initAttributes() + { + $keys = array_merge(...array_values($this->bitFlags)); + $this->_attributes = array_fill_keys($keys, null); + } public function events() { @@ -94,6 +116,38 @@ class BitFlagBehavior extends Behavior } return $bitFlagValue; } + + /** + * {@inheritdoc} + */ + public function __get($name) + { + return $this->_attributes[$name]; + } + + /** + * {@inheritdoc} + */ + public function __set($name, $value) + { + $this->_attributes[$name] = $value; + } + + /** + * {@inheritdoc} + */ + public function canGetProperty($name, $checkVars = true) + { + return parent::canGetProperty($name, $checkVars) || ArrayHelper::keyExists($name, $this->_attributes); + } + + /** + * {@inheritdoc} + */ + public function canSetProperty($name, $checkVars = true) + { + return parent::canSetProperty($name, $checkVars) || ArrayHelper::keyExists($name, $this->_attributes); + } } ``` @@ -107,18 +161,6 @@ use {yourApp}\behaviors\BitFlagBehavior; class MyModel extends base\MyModel { - /** - * @var int 状态 - */ - public $s0; - public $s1; - public $s2; - public $s3; - public $s5; - public $s6; - public $s7; - public $s8; - /** * 位标志映射表: * [ @@ -144,10 +186,10 @@ class MyModel extends base\MyModel { $fields = parent::fields(); $flagFields = []; - foreach (self::BIT_FLAGS as $bitFlag) { - $flagFields = ArrayHelper::merge($flagFields, array_combine($bitFlag, $bitFlag)); + foreach (self::BIT_FLAGS as $bitFlag => $flags) { + $flagFields = ArrayHelper::merge($flagFields, array_combine($flags, $flags)); + unset($fields[$bitFlag]); } - unset($fields['bit_flag']); return ArrayHelper::merge($fields, $flagFields); }