YII2 實現後臺操做記錄日誌

1、鏈接linux服務器,建立數據文件 php

  php yii migrate/create user_logmysql

  

2、修改數據文件linux

console/migrations/m150721_032220_admin_log.phpweb

<?php

use yii\db\Schema;
use yii\db\Migration;

class m150721_032220_admin_log extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="後臺操做記錄"';
        }

        $this->createTable('{{%admin_log}}', [
            //'name'=>Schema::TYPE_STRING.'(200) PRIMARY KEY NOT NULL',
            'id'=>Schema::TYPE_PK,
            'admin_id'=>Schema::TYPE_INTEGER.'(10) UNSIGNED NOT NULL COMMENT "操做用戶ID"',
            'admin_name'=>Schema::TYPE_STRING.'(200) NOT NULL COMMENT "操做用戶名"',
            'addtime'=>Schema::TYPE_INTEGER.'(10) NOT NULL COMMENT "記錄時間"',
            'admin_ip'=>Schema::TYPE_STRING.'(200) NOT NULL COMMENT "操做用戶IP"',
            'admin_agent'=>Schema::TYPE_STRING.'(200) NOT NULL COMMENT "操做用戶瀏覽器代理商"',
            'title'=>Schema::TYPE_STRING.'(200) NOT NULL COMMENT "記錄描述"',
            'model'=>Schema::TYPE_STRING.'(200) NOT NULL COMMENT "操做模塊(例:文章)"',
            'type'=>Schema::TYPE_STRING.'(200) NOT NULL COMMENT "操做類型(例:添加)"',
            'handle_id'=>Schema::TYPE_INTEGER.'(10) NOT NULL COMMENT "操做對象ID"',
            'result'=>Schema::TYPE_TEXT.' NOT NULL COMMENT "操做結果"',
            'describe'=>Schema::TYPE_TEXT.' NOT NULL COMMENT "備註"',

        ], $tableOptions);
    }

    public function down()
    {
        $this->dropTable('{{%admin_log}}');
    }
}

 3、根據數據文件生成數據表sql

  php yii migratejson

  

4、建立操做記錄的控制器、模型、視圖瀏覽器

  控制器服務器

  

<?php

namespace backend\controllers;

use backend\components\BaseController;
use common\models\AdminLog;
use yii;
use yii\data\ActiveDataProvider;

class AdminLogController extends BaseController
{
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => AdminLog::find(),
            'sort' => [
                'defaultOrder' => [
                    'addtime' => SORT_DESC
                ]
            ],
        ]);
        return $this->render('index',[
            'dataProvider' => $dataProvider
        ]);
    }

    public function actionView($id){
       return $this->render('view',[
           'model'=>AdminLog::findOne($id),
       ]);
    }

}

模型session

<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%article}}".
 **/
class AdminLog extends \yii\db\ActiveRecord
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%admin_log}}';
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id'=>'操做記錄ID',
            'title'=>'操做記錄描述',
            'addtime'=>'記錄時間',
            'admin_name'=>'操做人姓名',
            'admin_ip'=>'操做人IP地址',
            'admin_agent'=>'操做人瀏覽器代理商',
            'controller'=>'操做控制器名稱',
            'action'=>'操做類型',
            'objId'=>'操做數據編號',
            'result'=>'操做結果',
        ];
    }



    public static function saveLog($controller ,$action,$result,$objId){
        $model = new self;
        $model->admin_ip = Yii::$app->request->userIP;
        $headers = Yii::$app->request->headers;
        $model->addtime = time();
        if ($headers->has('User-Agent')) {
            $model->admin_agent =  $headers->get('User-Agent');
        }
        $model->admin_id = Yii::$app->user->identity->id;
        $model->admin_name = Yii::$app->user->identity->email;

        $controllers = ['article','video','collection','collection-album','category','banner','exchange','user','admin'];
        if(!in_array(strtolower($controller),$controllers)) $controller = '';
        $actions = ['create','update','delete','login','logout'];
        if(!in_array(strtolower($action),$actions))$action = '';

        $model->controller = $controller;
        $model->action = $action;
        $model->result = $result;
        $model->objId = $objId;
        $model->title =  $model->admin_name.' '.$model->action.' '.$model->controller;
        $model->save(false);

    }
}

視圖app

index視圖

<?php use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = '操做記錄'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="handle-index"> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'title', [ 'attribute'=>'addtime', 'value'=>function($model){ return date('Y-m-d H:i:s',$model->addtime); }, ], ['class' => 'yii\grid\ActionColumn','template'=>'{view}'] ], 'tableOptions'=>['class' => 'table table-striped'] ]); ?> </div>
view視圖

<?php use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model backend\models\Admin */ $this->title = '操做記錄: '.$model->title; $this->params['breadcrumbs'][] = ['label' => '操做記錄', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="admin-view"> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'admin_name', 'addtime:datetime', 'admin_ip', 'admin_agent', 'controller', 'action', 'objId', 'result' ], ]) ?> </div>

5、實現記錄添加

控制器中調用

public
function actionCreate() { $model = new Banner(); $model->status=Banner::STATUS_DISPLAY; if ($model->load(Yii::$app->request->post()) && $model->save()) { //保存操做記錄 \common\models\AdminLog::saveLog('banner','create',$model->searchById($model->primaryKey),$model->primaryKey); Yii::$app->session->setFlash('success','Banner【'.$model->title.'】發佈成功'); return $this->redirect(['index']); } else { return $this->render('create', [ 'model' => $model, ]); } }
public function searchById($id){    if (($model = Banner::findOne($id)) !== null) {        return json_encode($model->toArray());    } else {        throw new \yii\web\NotFoundHttpException('The requested page does not exist.');    }}
相關文章
相關標籤/搜索