文档章节

laravel实战化项目之三板斧

火腿骑士
 火腿骑士
发布于 2016/11/20 14:55
字数 3823
阅读 8
收藏 0
点赞 0
评论 0

laravel实战化项目之三板斧

spring mvc 实战化项目之三板斧

asp.net mvc 实战化项目之三板斧

laravel是我工作10多年来见到的真正能称得上让phper从面条一样杂乱的代码中解脱出来,虽然我不是完全的phper;并真正意义上的一个比较完美优雅的基于面向对象又mvc富有表现力的强大的PHP开发框架。

laravel安装配置这里就略过不表啦。本文希望从一张表(tb_role_info 用户角色表)的CRUD展开laravel的绅士魅力。

开发技术选型:laravel framework5+bootstrap+mysql。

项目目录结构:

喔忘了views视图层,存放表现页面。

(1)业务表 tb_role_info

复制代码

1 -- ----------------------------
 2 -- Table structure for `tb_role_info` 用户角色表
 3 -- ----------------------------
 4 DROP TABLE IF EXISTS `tb_role_info`;
 5 CREATE TABLE `tb_role_info` (
 6   `id` int(11) NOT NULL AUTO_INCREMENT,
 7   `role_name` varchar(32) NOT NULL DEFAULT '' COMMENT '角色名称',
 8   `role_mark` varchar(255) DEFAULT '' COMMENT '角色备注',
 9   `creater_id` int(11) NOT NULL DEFAULT '0' COMMENT '记录创建者id',
10   `created_at` timestamp NULL DEFAULT NULL COMMENT '创建日期',
11   `updated_at` timestamp NULL DEFAULT NULL COMMENT '更新日期',
12   `time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '记录更新时间戳',
13   PRIMARY KEY (`id`),
14   KEY `tb_role_info_index` (`id`,`role_name`,`creater_id`) USING BTREE
15 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='角色信息表';

复制代码

(2)业务界面 role.blade.php

复制代码

<!DOCTYPE html>
<html>
<head>
    @include('backend.header')
    <link rel="stylesheet" type="text/css" href="{{asset('backend/plugs/bootstrap-table/src/bootstrap-table.css')}}?v={{$version}}"/>
</head>
<body>
    @include('backend.navbar')
    <div id="page-container">
    <!-- BEGIN SIDEBAR -->
       @include('backend.menu')
    <!-- END SIDEBAR -->
        <!-- BEGIN RIGHTBAR -->
        <!-- END RIGHTBAR -->
        <div id="page-content">
            <div id="wrap">
                <div id="page-heading">
                    <ol class="breadcrumb">
                        <li><a href="#" title="icons">系统管理</a></li>
                        <li class="active">角色信息</li>
                    </ol>
                </div>
                <!-- container 内容显示区域begin-->
                <div class="container">
                    <div class='data-loading'></div>
                   <div class="row">
                           <div class="col-xs-12">
                        <div id="search_panel" class="search-panel-body">
                               <form id="search_form" class="form-horizontal">
                                   <div class="row">
                                    <div class="col-md-10">
                                        <div class="form-group">
                                            <label for="search_txt_roleName" class="col-sm-1 control-label">角色名称</label>
                                            <div class="col-sm-11">
                                                <input id="search_txt_roleName"  type="text" class="form-control" placeholder="请输入关键字...">
                                            </div>
                                        </div>
                                    </div>
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                   <div class="col-sm-8">
                                                     <button id="btn_search_save" type="button" class="btn btn-primary"> <i class="fa fa-search"></i> 查询</button>
                                               </div>
                                                <div class="col-sm-4">
                                                   <button id="btn_search_expand" type="button" class="btn btn-default"> <i class="fa fa-angle-double-up"></i></button>
                                                 </div>
                                             </div>
                                         </div>
                                    </div>
                                   <div class="row" id="search_more_panel" style="display:none;">
                                   </div>
                                 </form>
                               </div>
                            <div class="panel panel-gray">
                                <div class="panel-heading">
                                    <h4>角色信息 </h4>
                                    <div class="options">
                                        <div class="btn-group">
                                                  <div class="btn-group" id="table_tools_bar">
                                                    <button type="button" class="btn btn-default dropdown-toggle btn-tools" data-toggle="dropdown" title="定制列显示"><i class="fa fa-th-list"></i> <span class="caret"></span></button>
                                                </div>
                                              <button id="btn_role_refresh" type="button" class="btn btn-default btn-tools" title="角色刷新"><i class="fa fa-refresh"></i></button>
                                           </div>
                                    </div>
                                    <div class="options options-groups">
                                        <a href="javascript:;" id="btn_role_delete" title="角色删除"><i class="fa fa-times"></i> 删除</a> 
                                        <a data-toggle="modal" href="#form_modal" id="btn_role_edit" title="角色编辑"><i class="fa fa-edit"></i> 编辑</a> 
                                        <a data-toggle="modal" href="#form_modal" id="btn_role_add" title="角色添加"><i class="fa fa-pencil"></i> 添加</a> 
                                    </div>
                                </div>
                                <div class="panel-body">
                                    
                                    <div class="table-responsive">
                                        <table id="role_table"></table>
                                    </div>
                                    <!-- add/edit modal-begin -->
                                    <div id="form_modal" class="modal fade md-trigger"
                                        data-modal="md-fade-in-scale-up"
                                        tabindex="-1" 
                                        role="dialog" 
                                        aria-labelledby="form_modal_title" 
                                        data-keyboard="true"
                                        data-backdrop="static" 
                                        aria-hidden="true">

                                        <div id="form_modal_dialog" class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                                        ×</button>
                                                    <h4 class="modal-title" id="form_modal_title"></h4>
                                                </div>
                                                <div class="modal-body">
                                                    <form id="modalForm" class="form-horizontal" role="form" enctype="multipart/form-data">
                                                        <!-- 隐藏值存放区域  begin-->
                                                        <input name="id" id="form_hidden_id" type="hidden">
                                                        <input name="createrId" id="form_hidden_createrId" type="hidden">
                                                         <!-- 隐藏值存放区域 end-->
                                                        <div class="form-group">
                                                            <label for="form_txt_roleName" class="col-sm-2 control-label">角色名称</label>
                                                            <div class="col-sm-7">
                                                              <input id="form_txt_roleName" name="roleName" maxlength="32" placeholder="角色名称最多32个字符" required="" type="text" class="form-control">
                                                            </div>
                                                            <div class="col-sm-3">
                                                                <p class="help-block">角色名称必填!</p>
                                                            </div>
                                                        </div>
                                                        <div class="form-group">
                                                            <label for="form_txt_roleName" class="col-sm-2 control-label">角色权限</label>
                                                            <div class="col-sm-10">
                                                             <table id="table_module" class="table table-bordered">
                                                                    <thead>
                                                                        <tr>
                                                                            <th width="2%" style="padding: 10px">
                                                                            
                                                                            </th>
                                                                            <th width="28%" style="padding: 10px">
                                                                                模块
                                                                            </th>
                                                                                <th width="30%" style="padding: 10px">
                                                                                功能
                                                                            </th>
                                                                                <th width="30%" style="padding: 10px">
                                                                                动作
                                                                            </th>
                                                                        </tr>
                                                                    </thead>
                                                                    @if(isset($moduleList))
                                                                    <tbody>
                                                                        @foreach($moduleList as $module)
                                                                            @if($module->id==1 && $user->userRoleId!=1)
                                                                              
                                                                            @else 
                                                                                <tr>
                                                                                    <td>
                                                                                        <input type="checkbox" id="power_{{$module->id}}" name="mod_{{$module->id}}" value="{{$module->id}}" onclick="checkModule({{$module->id}});" />
                                                                                    </td>
                                                                                    <td>
                                                                                        {{$module->moduleCnName}}
                                                                                    </td>
                                                                                    <td>
                                                                                        <table width="100%">
                                                                                            @if(isset($module->children))
                                                                                                @foreach($module->children as $children) 
                                                                                                <tr>
                                                                                                    <td width="6%"><input type="checkbox" id="power_{{$children->id}}" name="fun_{{$module->id}}" value="{{$children->id}}" onclick="checkFun({{$module->id}});" /></td>
                                                                                                    <td width="94%">{{$children->moduleCnName}}</td>
                                                                                                </tr>
                                                                                                @endforeach
                                                                                            @endif
                                                                                         </table>
                                                                                  </td>
                                                                                 <td>
                                                                                         <table width="100%">
                                                                                            @if(isset($module->children))
                                                                                                @foreach($module->children as $oneChild) 
                                                                                                    @if(isset($oneChild->children)) 
                                                                                                            @foreach($oneChild->children as $twoChild)
                                                                                                             <tr>
                                                                                                                <td width="6%"><input type="checkbox" id="power_{{$twoChild->id}}" name="act_{{$children->id}}" value="{{$twoChild->id}}"  onclick="checkAction({{$children->id}});"/></td>
                                                                                                                <td width="94%">{{$twoChild->moduleCnName}}</td>
                                                                                                             </tr>
                                                                                                            @endforeach
                                                                                                     @endif 
                                                                                                @endforeach
                                                                                            @endif
                                                                                         </table>
                                                                                    </td>
                                                                                </tr>
                                                                            @endif
                                                                         @endforeach
                                                                    </tbody>
                                                                  @endif
                                                                </table>
                                                            </div>
                                                        </div>
                                                        <div class="form-group">
                                                            <label for="form_txt_roleMark" class="col-sm-2 control-label">
                                                                角色描述</label>
                                                            <div class="col-sm-10">
                                                                    <textarea  id="form_txt_roleMark" name="roleMark" maxlength="255" placeholder="角色描述最多255个字符" class="form-control autosize"></textarea>
                                                            </div>
                                                        </div>
                                                    </form>
                                                </div>
                                                <div class="modal-footer">
                                                    <button id="btn_role_save" type="button" class="btn btn-primary">
                                                        确定</button>
                                                    <button type="button" class="btn btn-default" data-dismiss="modal">
                                                        取消</button>
                                                </div>
                                            </div>
                                            <!-- /.modal-content -->
                                        </div>
                                        <!-- /.modal-dialog -->
                                    </div>
                                  <!-- add/edit modal-end -->

                                </div>
                            </div>
                        </div>
                   </div>
                </div>
                <!-- container 内容显示区域end-->
            </div>
            <!--wrap -->
        </div>
    </div>
    <!-- page-container -->
    <!-- page-content -->
   @include('backend.footer')
</body>
</html>
<script type="text/javascript" charset="utf-8" src="{{asset('backend/plugs/bootstrap-table/src/bootstrap-table.js')}}?v={{$version}}"></script>
<script type="text/javascript" charset="utf-8" src="{{asset('backend/plugs/bootstrap-table/src/locale/bootstrap-table-zh-CN.js')}}?v={{$version}}"></script>
<script type="text/javascript" charset="utf-8" src="{{asset('backend/js/sys_role.js')}}?v={{$version}}"></script>

复制代码

(3)业务界面逻辑 sys_role.js

谁总是说用了jquery会导致你的脚本代码像意大利面条呀。你看像吗?!像也只能说明你功底不够。软件架构设计规划能力太差。

复制代码

/**
* sys_role
* 角色信息
* @author steven9801@163.com
* @date 2015-11-19
*/
(function ($) {
    $(document).ready(function () {
        /**
        * 初始化
        */
        init();
        /**
        * 新建模态
        */
        $('#btn_role_add').click(function () {
            addModal()
        });
        /**
        * 编辑模态
        */
        $('#btn_role_edit').click(function () {
            var rowList = dataGrid.bootstrapTable('getSelections');
            var length = rowList.length;
            if (length == 0) {
                warningBox('请选择编辑对象.');
                return false;
            }
            if (length > 1) {
                warningBox('只能编辑一项.');
                return false;
            }
            editModal(rowList[0]);
        });
        /**
        * 保存动作
        */
        $('#btn_role_save').click(function () {
            switch (dialogType) {
                case 'add':
                    onAdd();
                    break;
                case 'edit':
                    onEdit();
                    break;
                default:
                    break;
            }
        });
        /**
        * 删除
        */
        $('#btn_role_delete').click(function () {
            onDelete();
        });
        //-----------------常规事件----------begin-------//
        /**
        * 刷新
        */
        $('#btn_role_refresh').click(function () {
            dataGrid.bootstrapTable('destroy');
            loadGrid();
        });
        /**
        * 展开
        */
        $('#btn_search_expand').click(function () {
            $(this).html('');
            searchStatus = searchStatus ? false : true;
            if (searchStatus) {
                $('#search_more_panel').hide('slow');
                $(this).html('<i class="fa fa-angle-double-up"></i>');
            }
            else {
                $('#search_more_panel').show('slow');
                $(this).html('<i class="fa fa-angle-double-down"></i>');
            }
            return false;
        });
        /**
        * 提交查询
        */
        $('#btn_search_save').click(function () {
            dataGrid.bootstrapTable('destroy');
            bindGrid(function (params) {
                var roleName = $('#search_txt_roleName').val();
                role.pageSize = params.pageSize;
                role.pageStart = params.pageSize * (params.pageNumber - 1);
                role.sortName = params.sortName;
                role.sortOrder = params.sortOrder;
                if (roleName.length > 0) {
                    role.roleName = roleName;
                }
                return JSON.stringify(role);
            });
        });

        //-----------------常规事件----------end-------//
    });
})(jQuery);
/**
* 全局变量
*/
//--------------------------全局变量区---------------------------//
var dataGrid = null; //列表对象
var dialogType = 'add';
var role = {};
var lock = false; //防止重复提交
var searchStatus = false; //查询面板状态
//--------------------------全局变量区---------------------------//
/**
* 初始化
*/
function init() {
    loadGrid();
    $("#form_modal .modal-body").css({ height: "650px", overflowX: "hidden", overflowY: "auto" });
    $('textarea.autosize').autosize({ append: "\n" });
};
/**
* 
* 加载列表
* 
*/
function loadGrid() {
    bindGrid(function (params) {
        return JSON.stringify({
            pageSize: params.pageSize,
            pageStart: params.pageSize * (params.pageNumber - 1),
            sortName: params.sortName,
            sortOrder: params.sortOrder
        });
    });
    return false;
};



/**
* 绑定列表
*/
function bindGrid(callBack) {
    dataGrid = $('#role_table').bootstrapTable({
        method: 'POST',
        contentType: 'application/json;charset=utf-8',
        url: '../admin/role',
        height: 500,
        striped: true,
        pagination: true,
        sidePagination: 'server',
        pageSize: 25,
        pageList: [25, 50, 100, 200],
        showExport: true,
        sortName: 'createdAt',
        sortOrder: 'desc',
        minimunCountColumns: 2,
        formatLoadingMessage: function () {
            return '<img src="../../backend/images/loading.gif"/>';
        },
        queryParams: callBack,
        columns:
        [
        { field: 'state', checkbox: true },
        { field: 'roleName', title: '角色名称', align: 'left', valign: 'middle', sortable: true },
        { field: 'createdAt', title: '创建时间', align: 'center', valign: 'middle', sortable: true },
        { field: 'operate', title: '操作', align: 'left', valign: 'middle', sortable: false, formatter: formatOperate, events: operateEvents }
        ]
    });
};

/**
* 格式化操作列
* 
*/
function formatOperate(value, row, index) {
    var content = [];
    content.push(' <a class="view" data-toggle="modal" href="#form_modal" title="角色查看"><i class="fa fa-eye"></i></a>');
    content.push(' <a class="edit" data-toggle="modal" href="#form_modal" title="角色编辑"><i class="fa fa-edit"></i></a>');
    content.push(' <a class="delete" href="javascript:void(0)" title="角色删除"><i class="fa fa-times"></i></a>');
    return content.join('');
};

/**
* 操作列事件
*/
window.operateEvents = {
    'click .view': function (e, value, row, index) {
        viewModal(row);
        return false;
    },
    'click .edit': function (e, value, row, index) {
        editModal(row);
        return false;
    },
    'click .delete': function (e, value, row, index) {
        if (lock) return false;
        lock = true;
        if (userToken.id != row.createrId) {
            lock = false;
            warningBox('对不起,您无权删除该角色.');
            return false;
        }
        var ids = [];
        ids.push(row.id);
        var params = {};
        params.ids = ids;
        deleteModal(params);
    }
};

/**
* 显示模态
*/
function showModal(action, title, width) {
    dialogType = action;
    $('.modal-footer').show();
    $('#form_modal #form_modal_title').html(title);
    $('#form_modal_dialog').css({ width: width });
    $('select,textarea,input').prop('disabled', false);
    $('#back-to-top').trigger('click');
    return false;
};

/**
* 绑定模态
*/
function bindModal(row) {

    $('#form_hidden_id').val(row.id);
    $('#form_hidden_createrId').val(row.createrId);
    $('#form_txt_roleName').val(row.roleName);
    $('#form_txt_roleMark').val(row.roleMark);

    $("input[id^='power_']").removeAttr("checked");
    var roleModuleList = row.roleModuleList;
    for (var i in roleModuleList) {
        var id = roleModuleList[i];
        $("input[id='power_" + id + "']").prop("checked", true);
    }
};

/**
* 查看模态
*/
function viewModal(row) {
    showModal('view', '角色查看', '60%');
    bindModal(row);
    $('select,textarea,input:not(.fixed-table-container input)').prop('disabled', true);
    $('#search_panel select,#search_panel input').prop('disabled', false);
    $('#table_tools_bar').find('input').prop('disabled', false);
    $('.modal-footer').hide();
    return false;
};

/**
* 编辑模态
*/
function editModal(row) {
    role = row;
    if (userToken.id != row.createrId) {
        pauseModal('#form_modal');
        warningBox('对不起,您无权编辑该角色.');
        return false;
    }
    showModal('edit', '角色编辑', '60%');
    bindModal(row);
    return false;
};

/**
* 新建模态
*/
function addModal() {
    showModal('add', '角色新建', '60%');
    $('input[type=text],input[type=hidden],input[type=number],textarea').val('');
    $('select option').eq(0).prop('selected', true);
    $("input[id^='power_']").prop('checked', false);
    return false;
};

/**
* 验证表单
*/
function checkForm() {
    if (lock) return false;
    lock = true;
    var roleName = $("#form_txt_roleName").val();
    if (roleName.length == 0) {
        warningBox("角色名称不能为空.");
        lock = false;
        return false;
    }

    if (roleName.length > 32) {
        warningBox("角色名称最多32个字符.");
        lock = false;
        return false;
    }

    if ($("input[id^='power_']:checkbox:checked").length == 0) {
        warningBox("请选择权限.");
        lock = false;
        return false;
    }


    var roleMark = $("#form_txt_roleMark").val();
    if (roleMark.length > 255) {
        warningBox("角色描述最多255个字符.");
        lock = false;
        return false;
    }

    var roleModuleList = [];
    $("input[id^='power_']:checkbox:checked").each(function () {
        var id = parseInt($(this).val());
        roleModuleList.push(id);
    });

    role.roleName = roleName;
    role.roleMark = roleMark;
    role.roleModuleList = roleModuleList;
    return true;
};

/**
* 角色添加
*/
function onAdd() {
    if (!checkForm()) {
        return false;
    }
    $('.data-loading').show();
    var task = new DelayedTask(function () {
        $.ajax({
            cache: false,
            type: "POST",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            url: "../admin/role/add",
            data: JSON.stringify(role),
            timeout: 30000,
            success: function (data) {
                if (data) {
                    $(".data-loading").hide();
                    var code = data.code;
                    if (code != 0) {
                        dangerBox(data.message);
                        lock = false;
                        return false;
                    }
                    lock = false;
                    $('#form_modal').modal('hide')
                    successBox('角色新建成功.');
                    $('#btn_role_refresh').trigger('click');
                }
                return false;
            },
            error: function (e) {
                if (e.status == 404) {
                    window.location = "../../404.html";
                }
                else if (e.status == 500) {
                    window.location = "../../500.html";
                }
            }
        });
    });
    task.delay(500);
    return false;
};

/**
* 角色编辑
*/
function onEdit() {
    if (!checkForm()) {
        return false;
    }
    $('.data-loading').show();
    var task = new DelayedTask(function () {
        $.ajax({
            cache: false,
            type: "POST",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            url: "../admin/role/edit",
            data: JSON.stringify(role),
            timeout: 30000,
            success: function (data) {
                if (data) {
                    $(".data-loading").hide();
                    var code = data.code;
                    if (code != 0) {
                        dangerBox(data.message);
                        lock = false;
                        return false;
                    }

                    lock = false;
                    $('#form_modal').modal('hide')
                    successBox('角色编辑成功.');
                    $('#btn_role_refresh').trigger('click');
                }
                return false;
            },
            error: function (e) {
                if (e.status == 404) {
                    window.location = "../../404.html";
                }
                else if (e.status == 500) {
                    window.location = "../../500.html";
                }
            }
        });
    });
    task.delay(500);
    return false;
};

/**
* 角色删除
*/
function onDelete() {
    if (lock) return false;
    lock = true;
    var ids = [];
    var rowList = dataGrid.bootstrapTable('getSelections');
    var length = rowList.length;
    if (length == 0) {
        warningBox('请选择删除对象.');
        lock = false;
        return false;
    }
    var flag = false;
    for (var i in rowList) {
        var row = rowList[i];
        var createrId = row.createrId;
        if (userToken.id != createrId) {
            flag = true;
        }
        var id = row.id;
        ids.push(id);
    }
    if (flag) {
        warningBox('对不起,您无权删除该角色.');
        lock = false;
        return false;
    }
    var params = {};
    params.ids = ids;
    deleteModal(ids);
    return false;
};

/**
* 删除模态
*/
function deleteModal(ids) {
    confirmBox('您确定要删除吗?!', function (result) {
        if (result) {
            $('.data-loading').show();
            $.ajax({
                cache: false,
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                url: '../admin/role/delete',
                data: JSON.stringify(ids),
                timeout: 30000,
                success: function (data) {
                    if (data) {
                        $('.data-loading').hide();
                        var code = data.code;
                        if (code != 0) {
                            dangerBox(data.message);
                            lock = false;
                            return false;
                        }
                        lock = false;
                        successBox('角色删除成功.');
                        $('#btn_role_refresh').trigger('click');
                    }
                    return false;
                },
                error: function (e) {
                    if (e.status == 404) {
                        window.location = '../../404.html';
                    }
                    else if (e.status == 500) {
                        window.location = '../../500.html';
                    }
                }
            });
        }
        else {
            lock = false;
        }
    });
    return false;
};



/**
* 选择模块
*/
function checkModule(moduleId) {
    $("input[name='fun_" + moduleId + "']").each(function () {
        if ($(this).is(":checked") == true) {
            $(this).prop("checked", false)
        }
        else {
            $(this).prop("checked", true);
        }
    });

};
/**
* 选择功能
*/
function checkFun(moduleId) {
    var funLength = $("input[name='fun_" + moduleId + "']:checkbox:checked").length;
    if (funLength != 0) {
        $("input[name='mod_" + moduleId + "']").prop("checked", true);
    }
    else {
        $("input[name='mod_" + moduleId + "']").prop("checked", false);
    }
};

/**
* 选择动作
*/
function checkAction(funId) {
    var actLength = $("input[name='act_" + funId + "']:checkbox:checked").length;
    if (actLength != 0) {
        $("input[id='power_" + funId + "']").prop("checked", true);
    }
    else {
        $("input[id='power_" + funId + "']").prop("checked", false);
    }

};

复制代码

(4)业务控制器 RoleController.php

复制代码

<?php
/**
 * This is class RoleController
 * 角色控制器
 * @author steven9801@163.com
 * @date 2015-11-19
 * 
 */
class RoleController extends BaseController 
{
    private $roleInfoService = null;
    private $userInfoService = null;
    private $moduleInfoService = null;
    private $roleModuleService = null;
    private $transactionalService  = null;
    public function __construct()
    {
        if(is_null($this->userInfoService))
        {
            $this->userInfoService = new UserInfoService;
        }
        if(is_null($this->roleInfoService))
        {
            $this->roleInfoService = new RoleInfoService;
        }
        if(is_null($this->moduleInfoService))
        {
            $this->moduleInfoService = new ModuleInfoService;
        }
        if(is_null($this->roleModuleService))
        {
            $this->roleModuleService = new RoleModuleService;
        }
        if(is_null($this->transactionalService))
        {
            $this->transactionalService = new TransactionalService;
        }
    }
    
    /**
     * 角色界面
    */
    public function index()
    {
        if (!Auth::check()) 
        {
            return Redirect::to('admin/login');
        }
        
        $moduleList = $this->moduleInfoService->selectModuleInfo();
        if(!is_null($moduleList))
        {
            $moduleList = $this->objectToTree($moduleList);
        }
        
        return View::make('backend.role',array('sys' => $this->getConfigInfo()))
        ->with('version',Str::random(6))
        ->with('roleModuleList',$this->getRoleModuleInfo())
        ->with('user',Auth::user())
        ->with('moduleList',$moduleList);
    }
    
    /**
     * 角色列表
    */
    public function grid()
    {
        if (!Auth::check()) 
        {
            return Redirect::to('admin/login');
        }
        
        try 
        {
            $roleInfo = (object)Input::all();
            $userInfo = Auth::user();
            
            $sortName = $roleInfo->sortName;
            $sortOrder = $roleInfo->sortOrder;
            $pageStart = $roleInfo->pageStart;
            $pageSize = $roleInfo->pageSize;

            $where = function($query) use($roleInfo,$userInfo)
            {
                if(isset($roleInfo->roleName))
                {
                    $query->where('role_name','like','%'.$roleInfo->roleName.'%');
                }
            };
            
            $total = $this->roleInfoService->getRoleInfoCount($where);
            $roleInfoList = $this->roleInfoService->searchRoleInfo($where,$sortName,$sortOrder,$pageStart,$pageSize);
            $entityGrid = null;
            if(!is_null($roleInfoList)&&$roleInfoList->count()>0)
            {
                foreach($roleInfoList as $roleModel)
                {
                    $roleId  = $roleModel->id;
                    $where = function($query) use($roleId)
                    {
                        $query->where('role_id',$roleId);
                    };
                    $roleModuleListModel  = $this->roleModuleService->selectRoleModule($where);
                    if(!is_null($roleModuleListModel))
                    {
                        $roleModuleList = array();  
                        foreach($roleModuleListModel as $roleModule)
                        {
                            $roleModuleList[] = $roleModule->moduleId;
                        }
                        $roleModel->roleModuleList = $roleModuleList;
                    }
                }
                $entityGrid = $this->getEntityGrid($roleInfoList,$total);
            }
            else
            {
                $entityGrid = $this->getEntityGrid($roleInfoList);
            }
            $this->handlerResponseMessage($entityGrid);
            return $this->handlerResponseMessage($entityGrid);
        } 
        catch(Exception $e)
        {
            Log::error($e->getMessage());
            return $this->handlerFailMessage($e->getMessage());
        }
    }
    
    /**
     * 角色新建
    */
    public function add() 
    {
        if (!Auth::check()) 
        {
            return Redirect::to('admin/login');
        }
    
        try 
        {
            $roleInfo = (object)Input::all();
            $userInfo = Auth::user();
            
            $roleName = $roleInfo->roleName;
            $where = function($query) use($roleName)
            {
                $query->where('role_name',$roleName);
            };
            $roleInfoModel = $this->roleInfoService->getRoleInfo($where);
            if(!is_null($roleInfoModel))
            {
                throw new Exception('角色名称已存在.');
            }
            $roleInfo->createrId = $userInfo->id;
            $result = $this->transactionalService->insertRoleInfo($roleInfo);
            if($result==0)
            {
                throw new Exception('角色新建失败.');
            }
            $this->logSuccess();
            return $this->handlerSuccessMessage('../admin/role');
        } 
        catch(Exception $e)
        {
            $this->logFailed();
            Log::error($e->getMessage());
            return $this->handlerFailMessage($e->getMessage());
        }
    }

    /**
     * 角色编辑
    */
    public function edit() 
    {
        if (!Auth::check()) 
        {
            return Redirect::to('admin/login');
        }

        try 
        {
            $roleInfo = (object)Input::all();
            $userInfo = Auth::user();
            $result = $this->transactionalService->updateRoleInfo($roleInfo);
            if($result==0)
            {
                throw new Exception('角色编辑失败.');
            }
            $this->logSuccess();
            return $this->handlerSuccessMessage('../admin/role');
        } 
        catch(Exception $e)
        {
            $this->logFailed();
            Log::error($e->getMessage());
            return $this->handlerFailMessage($e->getMessage());
        }
    }
    
    /**
     * 角色删除
    */
    public function delete()
    {
        if (!Auth::check()) 
        {
            return Redirect::to('admin/login');
        }
        
        try 
        {
            $ids = (array)Input::all();
            $roleInfoList = $this->roleInfoService->selectRoleInfoByList($ids);
            if(is_null($roleInfoList)&&$roleInfoList->count()==0)
            {
                throw new Exception('角色删除失败.');
            }
            $result = $this->transactionalService->deleteRoleInfo($roleInfoList);
            if($result==0)
            {
                throw new Exception('角色删除失败.');
            }
            $this->logSuccess();
            return $this->handlerSuccessMessage('../admin/role');
        } 
        catch(Exception $e)
        {
            $this->logFailed();
            Log::error($e->getMessage());
            return $this->handlerFailMessage($e->getMessage());
        }
    }
}

复制代码

(5)业务实体层 RoleInfo.php

复制代码

<?php
/**
 * This is class RoleInfo
 * 角色实体类
 * @author steven9801@163.com
 * @date 2015-11-19
 */
class RoleInfo extends BaseModel
{
    protected $table = 'tb_role_info';
    protected $primaryKey = 'id';
    protected $softDelete = false;
    
    protected $roleModuleList = null;
}

复制代码

(6)业务数据层 RoleInfoDataProvider.php

复制代码

<?php
/**
 * This is class RoleInfoDataProvider
 * 角色数据驱动类
 * @author steven9801@163.com
 * @date 2015-11-19
 */
class RoleInfoDataProvider extends BaseDataProvider
{
    public function __construct() 
    {
        parent::__construct(new RoleInfo);
    }
    
    public function insertRoleInfo($model)
    {
        $roleInfo = new RoleInfo;
        $roleInfo->roleName = isset($model->roleName)?$model->roleName:'';
        $roleInfo->roleMark = isset($model->roleMark)?$model->roleMark:'';
        $roleInfo->createrId = isset($model->createrId)?$model->createrId:0;        
        return $roleInfo->save() ? $roleInfo -> id:0;    
    }

    public function updateRoleInfo($model)
    {
        if(!($model->id))
        {
            throw new Exception('参数id不能为空.');
        }
        $roleInfo = RoleInfo::find($model->id);
        if(is_null($roleInfo))
        {
            throw new Exception('[ID='.$model->id. ']不存在或者已被删除.');
        }
        if(isset($model->roleName))
        {
            $roleInfo->roleName = $model->roleName;
        }
        if(isset($model->roleMark))
        {
            $roleInfo->roleMark = $model->roleMark;
        }
        if(isset($model->createrId))
        {
            $roleInfo->createrId = $model->createrId;
        }
        return $roleInfo->save();
    }


    public function clearRoleInfo()
    {
        $roleInfoList = RoleInfo::all();
        if(is_null($roleInfoList))
        {
            throw new Exception('记录不存在或者已被删除.');
        }
        foreach($roleInfoList as $roleInfo)
        {
            $result = $roleInfo->delete();
            if(!$result)
            {
                break;
            }
        }
        return $result;
    }

    public function deleteRoleInfo($roleInfo)
    {
        return $roleInfo->delete();    
    }
    
    public function deleteRoleInfoByList($ids)
    {
        return RoleInfo::whereIn('id', $ids)->delete();    
    }
    
    public function getRoleInfo($where)
    {
        if(is_null($where))
        {
            return RoleInfo::first();
        }
        return RoleInfo::where($where)->first();
    }

    public function getRoleInfoCount($where)
    {
        if(is_null($where))
        {
            return RoleInfo::count();
        }
        return RoleInfo::where($where)->count();
    }
    
    public function selectRoleInfo($where,$sortName,$sortOrder)
    {
        if(is_null($where))
        {
            return RoleInfo::orderBy(snake_case($sortName),$sortOrder)->get();
        }
        return RoleInfo::where($where)->orderBy(snake_case($sortName),$sortOrder)->get();
    }
    
    public function selectRoleInfoByList($ids)
    {
        return RoleInfo::whereIn('id', $ids)->get();
    }

    public function searchRoleInfo($where, $sortName, $sortOrder, $pageStart, $pageSize)
    {
        if(is_null($where))
        {
            return RoleInfo::orderBy(snake_case($sortName),$sortOrder)->skip($pageStart)->take($pageSize)->get();
        }
        return RoleInfo::where($where)->orderBy(snake_case($sortName),$sortOrder)->skip($pageStart)->take($pageSize)->get();
    }
}

复制代码

(7)业务服务层 RoleInfoService.php

复制代码

<?php
/**
 * This is class RoleInfoService
 * 角色服务类
 * @author steven9801@163.com
 * @date 2015-11-19
 */
class RoleInfoService extends BaseService
{
    private $roleInfoDataProvider = null;

    public function __construct()
    {
        if(is_null($this->roleInfoDataProvider))
        {
            $this->roleInfoDataProvider = new RoleInfoDataProvider;
        }
        parent::__construct($this->roleInfoDataProvider);
    }
    
    public function insertRoleInfo($roleInfo)
    {
        $result = DB::transaction(function() use ($roleInfo) 
        {
            return $this->roleInfoDataProvider->insertRoleInfo($roleInfo);    
        });
        return $result;
    }
    
    public function insertRoleInfoBatch($roleInfoList) 
    {
        $result = DB::transaction(function() use ($roleInfoList) 
        {
            $insertedCount = 0;
            $changed = 0;
            foreach($roleInfoList as $roleInfo)
            {
                $changed = $this->roleInfoDataProvider->insertRoleInfo($roleInfo);
                if ($changed < 1) 
                {
                    return 0;
                }
                $insertedCount++;
            }
            return $insertedCount;
        });
        return $result;
    }
    
    public function updateRoleInfo($roleInfo)
    {
        $result = DB::transaction(function() use ($roleInfo) 
        {
            return $this->roleInfoDataProvider->updateRoleInfo($roleInfo);
        });
        return $result;
    }

    public function updateRoleInfoBatch($roleInfoList) 
    {
        $result = DB::transaction(function() use ($roleInfoList) 
        {
            $updatedCount = 0;
            $changed = 0;
            foreach($roleInfoList as $roleInfo)
            {
                $changed = $this->roleInfoDataProvider->updateRoleInfo($roleInfo);
                if ($changed < 1) 
                {
                    return 0;
                }
                $updatedCount++;
            }
            return $updatedCount;
        });
        return $result;
    }

    public function clearRoleInfo()
    {
        $result = DB::transaction(function() use ($roleInfo) 
        {
            return $this->roleInfoDataProvider->clearRoleInfo();    
        });
        return $result;
    }

    public function deleteRoleInfo($roleInfo)
    {
        $result = DB::transaction(function() use ($roleInfo) 
        {
            return $this->roleInfoDataProvider->deleteRoleInfo($roleInfo);
        });
        return $result;
    }
    
    public function deleteRoleInfoByList($ids)
    {
        $result = DB::transaction(function() use ($ids) 
        {
            return $this->roleInfoDataProvider->deleteRoleInfoByList($ids);
        });
        return $result;
    }
    
    public function deleteRoleInfoBatch($roleInfoList) 
    {
        $result = DB::transaction(function() use ($roleInfoList) 
        {
            $deletedCount = 0;
            $changed = 0;
            foreach($roleInfoList as $roleInfo)
            {
                $changed = $this->roleInfoDataProvider->deleteRoleInfo($roleInfo);
                if ($changed < 1) 
                {
                    return 0;
                }
                $deletedCount++;
            }
            return $deletedCount;
        });
        return $result;
    }
    
    public function getRoleInfo($where=null)
    {
        return $this->roleInfoDataProvider->getRoleInfo($where);
    }

    public function getRoleInfoCount($where=null)
    {
        return $this->roleInfoDataProvider->getRoleInfoCount($where);
    }
    
    public function selectRoleInfo($where=null,$sortName='id',$sortOrder='desc')
    {
        return $this->roleInfoDataProvider->selectRoleInfo($where,$sortName,$sortOrder);
    }
    
    public function selectRoleInfoByList($Ids)
    {
        return $this->roleInfoDataProvider->selectRoleInfoByList($Ids);
    }

    public function searchRoleInfo($where=null, $sortName='id', $sortOrder='desc', $pageStart=0, $pageSize=25)
    {
        return $this->roleInfoDataProvider->searchRoleInfo($where, $sortName, $sortOrder, $pageStart, $pageSize);
    }
}

复制代码

就这样简单整个业务表的CRUD结构清晰的完整的呈现在你面前啦。管中窥豹,真正拥有者会如获至宝。

敬请期待下期:
spring mvc 实战化项目之三板斧

asp.net mvc 实战化项目之三板斧

感兴趣的朋友扫下面的二维码给点打赏吧!

                  

虽功未成,亦未敢藏私,众侠诸神通尽录于此,竟成一笈,名葵花宝典,以飨后世。 
邮箱:steven9801@163.com 
QQ: 48039387

© 著作权归作者所有

共有 人打赏支持
火腿骑士
粉丝 0
博文 4
码字总数 14614
作品 0
嘉定
部门经理
asp.net mvc 实战化项目之三板斧

laravel实战化项目之三板斧 spring mvc 实战化项目之三板斧 asp.net mvc 实战化项目之三板斧 接上文希望从一张表(tbroleinfo 用户角色表)的CRUD展开asp.net mvc的项目实战化魅力。 开发技术...

火腿骑士
2016/11/20
7
0
Flask入门request session cookie(二)

1 HTTP方法分类 2 访问请求数据request 3 文件上传 5.2 cookie之三板斧 设置cookie: set_cookie

善良小郎君
05/29
0
0
PHP 框架--HunterPHP

我不知道什么样的形容词可以形容它的强大!十年web开发历程,终造得HunterPHP毁天一剑! cms 界的NO.1 --- Drupal 8! 没错,我研究多年,终究还是不满意,于是乎在Drupal基础上,吸取其精华...

Drupal猎人
2017/09/05
1K
12
php&go&python&node

2016 第二届 PHP 全球开发者大会回顾(文末附演讲嘉宾所有资料下载) 继前年的 “PHP7 初探”、去年的“高性能的 PHP ” 主题后,2017 第三届 PHP 全球开发者大会的活动主题是“高可用的 PH...

掘金官方
2017/12/20
0
0
手把手教你跑 Larave 框架实战笔记系列之一

         [宗旨]严格遵循现代编程组件化Web开发原理,通过phpRE+Composer + PhpStorm+Laravel快捷安装配置集成强大现代优雅开发平台,实现一站式Web开发。 [前 言]据调查显示,目...

人可工作室
06/26
0
0
Laravel5.4实战快速开发自媒体网站教程 Laravel实战教程

第1章 课程介绍 介绍课程的大体脉络和课程安排 第2章 Laravel 5.4介绍 本节课会带领大家介绍laravel的各个版本历史以及讨论php框架的未来发展趋势。把laravel周边的生态环境一一展示。 第3章...

15543595340
05/19
0
0
第3课:通过案例对SparkStreaming 透彻理解三板斧之三:解密SparkStreaming

第一部份 课堂的第一部份是用IMF 晚上案例实战课的程序再运行一次,把数据再次输入数据库里面,从图一你可以看出里面有很多运行细节,例如receiver.ReceiverSupervisor,receiver.BlockManag...

jcchoiling
2016/05/09
56
0
Laravel Composer Package 开发实战 toastr-for-laravel5

本文原链接来自我的博客,地址: Laravel Composer Package 开发实战 toastr-for-laravel5 在Laravel的文档中有Package Development,对于入门开发人员来说还是比较抽象,因为开发一个包需要了...

Yuansir
2016/01/22
216
0
想当程序员?从这里入门吧!

想当程序员? 没找到合适的入门教程? 实验楼上有啊,各技术入门教程~ 【C 语言入门教程】 C语言,不用多介绍,大多数人的入门语言;除了入门教程,还有很多实战项目教程呢,学完基础直接动手...

实验楼
2017/11/21
0
0
Laravel5学生成绩管理系统-05-分页

在其它的框架中,分页是非常让人苦恼的。而在 Laravel 中却是很轻而易举的。 Laravel 可以快速生成基于当前页面链接的智能「范围」,并且生成的 HTML 兼容于 Bootstrap CSS 框架。本项目中,...

Corwien
2016/05/21
77
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

对基于深度神经网络的Auto Encoder用于异常检测的一些思考

一、前言 现实中,大部分数据都是无标签的,人和动物多数情况下都是通过无监督学习获取概念,故而无监督学习拥有广阔的业务场景。举几个场景:网络流量是正常流量还是攻击流量、视频中的人的...

冷血狂魔
12分钟前
0
0
并发设计之A系统调用B系统

A-->B A在发送请求之前,用乐观锁,减少对B的重复调用,这样一定程度上是幂等性。 比如A系统支付功能,要调用B系统进行支付操作,但是前端对"支付"按钮不进行控制,即用户会不断多次点击支付...

汉斯-冯-拉特
32分钟前
0
0
HTTP协议通信原理

了解HTTP HTTP(HyperText Transfer Protocol)是一套计算机通过网络进行通信的规则。计算机专家设计出HTTP,使HTTP客户(如Web浏览器)能够从HTTP服务器(Web服务器)请求信息和服务。 HTTP使用...

寰宇01
55分钟前
0
0
【Java动态性】之反射机制

一、Java反射机制简介

谢余峰
56分钟前
1
0
Centos 6.X 部署环境搭建

1.Linux学习笔记CentOS 6.5(一)--CentOS 6.5安装过程

IT追寻者
今天
0
0
博客即同步至腾讯云+社区声明

我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=8vy9bsmadbko...

xiaoge2016
今天
1
0
大数据教程(3.1):Linux系统搭建网络YUM源服务器

博主在前面的2.5章节讲述了linux系统本地YUM服务器的搭建和httpd轻量级静态网站服务器的安装,本节博主将为大家分享内网环境中搭建自己的网络YUM服务器的全过程。如果大家对本地YUM服务器还不...

em_aaron
今天
1
0
蚂蚁技术专家:一篇文章带你学习分布式事务

小蚂蚁说: 分布式事务是企业集成中的一个技术难点,也是每一个分布式系统架构中都会涉及到的一个东西,特别是在这几年越来越火的微服务架构中,几乎可以说是无法避免,本文就围绕分布式事务...

Java大蜗牛
今天
1
0
新的Steam应用将拓展服务项目

导读 未来几周,Steam将推出两个免费的应用程序Steam Link和Steam Video。这两个应用程序都旨在拓展Steam平台的业务和便利性。 即将开放的Steam Link应用程序最先提供了Android测试版,它将允...

问题终结者
今天
0
0
golang 第三方包的使用总结

golang 第三方包的安装的方法: 1. go get 安装 $ go get github.com/gin-gonic/gin 注意:执行go get 命令需要先安装git命令,并配置git全局变量。 2. 源码包安装 由于国内网络问题,很多时...

科陆李明
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部