YII2 Implementing background operations Logging (GO)

Source: Internet
Author: User

One, connect the Linux server, create the data file

PHP yii migrate/create User_log

  

Second, modify the data file

console/migrations/m150721_032220_admin_log.php

<?phpuse 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 ENGI        Ne=innodb comment= "background operation Record"; } $this->createtable (' {{%admin_log}} ', [//' name ' =>schema::type_string. ' PRIMARY KEY not NULL ', ' id ' =>schema::type_pk, ' admin_id ' =>schema::type_integer. ' (Ten) UNSIGNED not NULL COMMENT "Operation User ID" ', ' Admin_name ' =>schema::type_string. ' (+) Not NULL COMMENT "Operation user name" ', ' Addtime ' =>schema::type_integer. ' (ten) Not NULL COMMENT "record Time" ', ' admin_ip ' =>schema::type_string. ' (+) Not NULL COMMENT "Operation User IP" ', ' admin_agent ' =>schema::type_string. ' (+) Not NULL COMMENT "Operation user browser Agent" ', ' title ' =>schema::type_string. ' (+) not NULL COMMENT "record description" ', ' model ' =Schema::type_string. ' (+) Not NULL COMMENT "Operation Module (example: article)" ', ' type ' =>schema::type_string. ' (+) Not NULL COMMENT "operation type (example: Add)" ', ' handle_id ' =>schema::type_integer. ' (ten) Not NULL COMMENT "operand id" ', ' result ' =>schema::type_text. ' Not NULL COMMENT "operation result" ', ' describe ' =>schema::type_text. '    Not NULL COMMENT "Remarks" ',], $tableOptions);    The public function is down () {$this->droptable (' {{%admin_log}} '); }}

  

Third, generate data table according to data file

PHP Yii Migrate

  

Iv. creating the controller, model, and view of the action record

Controller

<?phpnamespace 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),       ]);    }}

Model

<?phpnamespace 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 ' = ' = ' Operation record ID ', ' title ' = ' Operation record description ', ' addtime ' = ' record time ', ' admin_name ' = ' operator ' name ', ' Admin_i P ' = ' operator IP address ', ' admin_agent ' + ' operator browser agent ', ' controller ' = ' Operation controller name ', ' action ' =&gt ;‘    Operation type ', ' objId ' = ' Operation data number ', ' result ' = ' operation 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); }}

View

Index view <?phpuse yii\grid\gridview;/* @var $this yii\web\view *//* @var $dataProvider yii\data\activedataprovider */$ This->title = ' Operation record '; $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 View <?phpuse yii\widgets\detailview;/* @var $this yii\web\view *//* @var $model backend\models\admin */$this title = ' Operation record: '. $model->title; $this->params[' breadcrumbs ' [] = [' label ' + ' action record ', ' 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>

V. Implementation of record additions

The controller calls public function Actioncreate ()    {        $model = new Banner ();        $model->status=banner::status_display;        if ($model->load (Yii:: $app->request->post ()) && $model->save ()) {            //save operation Record            \common\ Models\adminlog::savelog (' banner ', ' Create ', $model->searchbyid ($model->primarykey), $model->primarykey) ;            Yii:: $app->session->setflash (' success ', ' Banner ', '. $model->title. ' "Successful release");            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. ');}    }

  

YII2 Implementing background operations Logging (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.