Browse Source

把字段移进Behavior

master
LIERLIER 1 year ago
parent
commit
99f360d321
  1. 72
      readme.md

72
readme.md

@ -24,6 +24,28 @@ class BitFlagBehavior extends Behavior
* @var array[] $bitFlags 位标志映射表 * @var array[] $bitFlags 位标志映射表
*/ */
public $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() public function events()
{ {
@ -94,6 +116,38 @@ class BitFlagBehavior extends Behavior
} }
return $bitFlagValue; 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 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(); $fields = parent::fields();
$flagFields = []; $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); return ArrayHelper::merge($fields, $flagFields);
} }

Loading…
Cancel
Save