laravel实战化项目之三板斧

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 实战化项目之三板斧

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

                  

posted @ 2016-10-26 15:08  火腿骑士  阅读(716)  评论(0编辑  收藏  举报