Laravel bootTraits 扩展应用

Laravel bootTraits

查看Model源码的时候可以看到:

/**
 * Boot all of the bootable traits on the model.
 *
 * @return void
 */
protected static function bootTraits()
{
    foreach (class_uses_recursive(get_called_class()) as $trait) {
        if (method_exists(get_called_class(), $method = 'boot'.class_basename($trait))) {
            forward_static_call([get_called_class(), $method]);
        }
    }
}

结合Model的事件,就可以实现一个通用的trait来记录系统的model的日志

 date('Y-m-d H:i:s'),
                    'FUserID' => Auth::id(),
                    'FDescription' => $model->getActionDescription($model, $event),
                    'FCreatorID' => Auth::id(),
                    'FCreateTime' => date('Y-m-d H:i:s')
                ]);
            });
        }
    }

    /**
     * 获取要响应的模型事件
     * @return array
     */
    protected static function getModelEvents()
    {
        if (isset(static::$recordEvents)) {
            return static::$recodrdEvents;
        }

        return ['created', 'updated', 'deleted'];
    }

    /**
     * 获取模型事件描述
     * @param $model
     * @param $event
     * @return string
     */
    protected function getActionDescription($model, $event)
    {
        if (method_exists($this, 'getCustomActionDescription')) {
            return $this->getCustomActionDescription($model, $event);
        }
        $className = strtolower((new \ReflectionClass($model))->getShortName());
        switch ($event) {
            case 'created':
                $object = json_encode($model);
                return "{$event}: {$className}, object: {$object}";
                break;
            case 'updated':
                $dirty = json_encode($model->getDirty());
                return "{$event}: {$className}, changed: {$dirty}";
                break;
            case 'deleted':
                $deleted = json_encode($model);
                return "{$event}: {$className}, previous: {$deleted}";
                break;
            default:
                return "{$event}: {$className}";
        }
    }

}

你可能感兴趣的:(Laravel bootTraits 扩展应用)