文档章节

yii2.0优化后台权限管理

botkenni
 botkenni
发布于 2017/02/28 18:33
字数 2068
阅读 122
收藏 0

原先的权限把控:必须把‘items'下的权限‘visible'都加进‘数据维护’下面去

                    [
                        'label' => '<i class="fa fa-edit"></i><span class="nav-label">数据维护</span>',

        'visible' => Yii::$app->user->can('product-category/list') || Yii::$app->user->can('region/list'),
                        'items' => [
                            [
                                'label' => '产品分类管理', 'url' => ['product-category/list'],
                                //'visible' => Yii::$app->user->isGuest
                            ],
                            [
                                'label' => '产品管理', 'url' => '#',
                                //'visible' => Yii::$app->user->isGuest
                                'visible' => Yii::$app->user->can('product-category/list'),
                            ],
                            [
                                'label' => '地区管理', 'url' => ['region/list'],
                                //'visible' => Yii::$app->user->isGuest
                            ],
                        ],
                    ],

然后权限把控在组件中

<?php
/**
 * Created by PhpStorm.
 * User: lixiang
 * Date: 2017/1/19
 * Time: 上午9:26
 */

namespace backend\widgets;

use imxiangli\metismenu\MetisMenuAsset;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Widget;
use yii\bootstrap\Html;
use yii\helpers\ArrayHelper;

class Nav extends Widget
{
    public $childOptions = [];

    /**
     * @var array list of items in the nav widget. Each array element represents a single
     * menu item which can be either a string or an array with the following structure:
     *
     * - label: string, required, the nav item label.
     * - url: optional, the item's URL. Defaults to "#".
     * - visible: boolean, optional, whether this menu item is visible. Defaults to true.
     * - linkOptions: array, optional, the HTML attributes of the item's link.
     * - options: array, optional, the HTML attributes of the item container (LI).
     * - active: boolean, optional, whether the item should be on active state or not.
     * - dropDownOptions: array, optional, the HTML options that will passed to the [[Dropdown]] widget.
     * - items: array|string, optional, the configuration array for creating a [[Dropdown]] widget,
     *   or a string representing the dropdown menu. Note that Bootstrap does not support sub-dropdown menus.
     * - encode: boolean, optional, whether the label will be HTML-encoded. If set, supersedes the $encodeLabels option for only this item.
     *
     * If a menu item is a string, it will be rendered directly without HTML encoding.
     */
    public $items = [];
    /**
     * @var boolean whether the nav items labels should be HTML-encoded.
     */
    public $encodeLabels = true;
    /**
     * @var boolean whether to automatically activate items according to whether their route setting
     * matches the currently requested route.
     * @see isItemActive
     */
    public $activateItems = true;
    /**
     * @var boolean whether to activate parent menu items when one of the corresponding child menu items is active.
     */
    public $activateParents = false;
    /**
     * @var string the route used to determine if a menu item is active or not.
     * If not set, it will use the route of the current request.
     * @see params
     * @see isItemActive
     */
    public $route;
    /**
     * @var array the parameters used to determine if a menu item is active or not.
     * If not set, it will use `$_GET`.
     * @see route
     * @see isItemActive
     */
    public $params;
    /**
     * @var string this property allows you to customize the HTML which is used to generate the drop down caret symbol,
     * which is displayed next to the button text to indicate the drop down functionality.
     * Defaults to `null` which means `<b class="caret"></b>` will be used. To disable the caret, set this property to be an empty string.
     */
    public $dropDownCaret;

    /**
     * @var array the HTML attributes for the widget container tag.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $options = [];


    /**
     * Initializes the widget.
     */
    public function init()
    {
        parent::init();
        if ($this->route === null && Yii::$app->controller !== null) {
            $this->route = Yii::$app->controller->getRoute();
        }
        if ($this->params === null) {
            $this->params = Yii::$app->request->getQueryParams();
        }
        if ($this->dropDownCaret === null) {
            $this->dropDownCaret = Html::tag('span', '', ['class' => 'fa arrow']);
        }
        Html::addCssClass($this->options, ['widget' => 'nav']);
    }

    /**
     * Renders the widget.
     */
    public function run()
    {
        MetisMenuAsset::register($this->getView());
        return $this->renderItems();
    }

    /**
     * Renders widget items.
     */
    public function renderItems()
    {
        $items = [];
        foreach ($this->items as $i => $item) {
            if (isset($item['visible']) && !$item['visible']) {
                continue;
            }
            $items[] = $this->renderItem($item);
        }

        return Html::tag('ul', implode("\n", $items), $this->options);
    }

    /**
     * Check to see if a child item is active optionally activating the parent.
     * @param array $items @see items
     * @param boolean $active should the parent be active too
     * @return array @see items
     */
    protected function isChildActive($items, &$active)
    {
        foreach ($items as $i => $child) {
            if (ArrayHelper::remove($items[$i], 'active', false) || $this->isItemActive($child)) {
                Html::addCssClass($items[$i]['options'], 'active');
                if ($this->activateParents) {
                    $active = true;
                }
            }
        }
        return $items;
    }

    /**
     * Checks whether a menu item is active.
     * This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
     * When the `url` option of a menu item is specified in terms of an array, its first element is treated
     * as the route for the item and the rest of the elements are the associated parameters.
     * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
     * be considered active.
     * @param array $item the menu item to be checked
     * @return boolean whether the menu item is active
     */
    protected function isItemActive($item)
    {
        if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
            $route = $item['url'][0];
            if ($route[0] !== '/' && Yii::$app->controller) {
                $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
            }
            if (ltrim($route, '/') !== $this->route) {
                return false;
            }
            unset($item['url']['#']);
            if (count($item['url']) > 1) {
                $params = $item['url'];
                unset($params[0]);
                foreach ($params as $name => $value) {
                    if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
                        return false;
                    }
                }
            }

            return true;
        }

        return false;
    }

    /**
     * Renders a widget's item.
     * @param string|array $item the item to render.
     * @return string the rendering result.
     * @throws InvalidConfigException
     */
    public function renderItem($item)
    {
        if (is_string($item)) {
            return $item;
        }
        if (!isset($item['label'])) {
            throw new InvalidConfigException("The 'label' option is required.");
        }
        $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
        $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
        $options = ArrayHelper::getValue($item, 'options', []);
        $items = ArrayHelper::getValue($item, 'items');
        $url = ArrayHelper::getValue($item, 'url', '#');
        $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []);

        if (isset($item['active'])) {
            $active = ArrayHelper::remove($item, 'active', false);
        } else {
            $active = $this->isItemActive($item);
        }

        if (empty($items)) {
            $items = '';
        } else {
            //$linkOptions['data-toggle'] = 'dropdown';
            //Html::addCssClass($options, ['widget' => 'dropdown']);
            //Html::addCssClass($linkOptions, ['widget' => 'dropdown-toggle']);
            if ($this->dropDownCaret !== '') {
                $label .= ' ' . $this->dropDownCaret;
            }
            if (is_array($items)) {
                if ($this->activateItems) {
                    $items = $this->isChildActive($items, $active);
                }
                $items = $this->renderChildren($items);

            }
        }

        if ($this->activateItems && $active) {
            Html::addCssClass($options, 'active');
        }

        return Html::tag('li', Html::a($label, $url, $linkOptions) . $items, $options);
    }

    public function renderChildren($children)
    {
        $items = [];
        foreach ($children as $i => $item) {
            if (isset($item['visible']) && !$item['visible']) {
                continue;
            }
            $items[] = $this->renderItem($item);
        }


        return Html::tag('ul', implode("\n", $items), $this->childOptions);
    }
}

优化之后的,在权限把控组件里面222行和243行2处新增了

if(empty($items)) return null;

优化后的:

<?php
/**
 * Created by PhpStorm.
 * User: lixiang
 * Date: 2017/1/19
 * Time: 上午9:26
 */

namespace backend\widgets;

use imxiangli\metismenu\MetisMenuAsset;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Widget;
use yii\bootstrap\Html;
use yii\helpers\ArrayHelper;

class Nav extends Widget
{
    public $childOptions = [];

    /**
     * @var array list of items in the nav widget. Each array element represents a single
     * menu item which can be either a string or an array with the following structure:
     *
     * - label: string, required, the nav item label.
     * - url: optional, the item's URL. Defaults to "#".
     * - visible: boolean, optional, whether this menu item is visible. Defaults to true.
     * - linkOptions: array, optional, the HTML attributes of the item's link.
     * - options: array, optional, the HTML attributes of the item container (LI).
     * - active: boolean, optional, whether the item should be on active state or not.
     * - dropDownOptions: array, optional, the HTML options that will passed to the [[Dropdown]] widget.
     * - items: array|string, optional, the configuration array for creating a [[Dropdown]] widget,
     *   or a string representing the dropdown menu. Note that Bootstrap does not support sub-dropdown menus.
     * - encode: boolean, optional, whether the label will be HTML-encoded. If set, supersedes the $encodeLabels option for only this item.
     *
     * If a menu item is a string, it will be rendered directly without HTML encoding.
     */
    public $items = [];
    /**
     * @var boolean whether the nav items labels should be HTML-encoded.
     */
    public $encodeLabels = true;
    /**
     * @var boolean whether to automatically activate items according to whether their route setting
     * matches the currently requested route.
     * @see isItemActive
     */
    public $activateItems = true;
    /**
     * @var boolean whether to activate parent menu items when one of the corresponding child menu items is active.
     */
    public $activateParents = false;
    /**
     * @var string the route used to determine if a menu item is active or not.
     * If not set, it will use the route of the current request.
     * @see params
     * @see isItemActive
     */
    public $route;
    /**
     * @var array the parameters used to determine if a menu item is active or not.
     * If not set, it will use `$_GET`.
     * @see route
     * @see isItemActive
     */
    public $params;
    /**
     * @var string this property allows you to customize the HTML which is used to generate the drop down caret symbol,
     * which is displayed next to the button text to indicate the drop down functionality.
     * Defaults to `null` which means `<b class="caret"></b>` will be used. To disable the caret, set this property to be an empty string.
     */
    public $dropDownCaret;

    /**
     * @var array the HTML attributes for the widget container tag.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $options = [];


    /**
     * Initializes the widget.
     */
    public function init()
    {
        parent::init();
        if ($this->route === null && Yii::$app->controller !== null) {
            $this->route = Yii::$app->controller->getRoute();
        }
        if ($this->params === null) {
            $this->params = Yii::$app->request->getQueryParams();
        }
        if ($this->dropDownCaret === null) {
            $this->dropDownCaret = Html::tag('span', '', ['class' => 'fa arrow']);
        }
        Html::addCssClass($this->options, ['widget' => 'nav']);
    }

    /**
     * Renders the widget.
     */
    public function run()
    {
        MetisMenuAsset::register($this->getView());
        return $this->renderItems();
    }

    /**
     * Renders widget items.
     */
    public function renderItems()
    {
        $items = [];
        foreach ($this->items as $i => $item) {
            if (isset($item['visible']) && !$item['visible']) {
                continue;
            }
            $items[] = $this->renderItem($item);
        }

        return Html::tag('ul', implode("\n", $items), $this->options);
    }

    /**
     * Check to see if a child item is active optionally activating the parent.
     * @param array $items @see items
     * @param boolean $active should the parent be active too
     * @return array @see items
     */
    protected function isChildActive($items, &$active)
    {
        foreach ($items as $i => $child) {
            if (ArrayHelper::remove($items[$i], 'active', false) || $this->isItemActive($child)) {
                Html::addCssClass($items[$i]['options'], 'active');
                if ($this->activateParents) {
                    $active = true;
                }
            }
        }
        return $items;
    }

    /**
     * Checks whether a menu item is active.
     * This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
     * When the `url` option of a menu item is specified in terms of an array, its first element is treated
     * as the route for the item and the rest of the elements are the associated parameters.
     * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
     * be considered active.
     * @param array $item the menu item to be checked
     * @return boolean whether the menu item is active
     */
    protected function isItemActive($item)
    {
        if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
            $route = $item['url'][0];
            if ($route[0] !== '/' && Yii::$app->controller) {
                $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
            }
            if (ltrim($route, '/') !== $this->route) {
                return false;
            }
            unset($item['url']['#']);
            if (count($item['url']) > 1) {
                $params = $item['url'];
                unset($params[0]);
                foreach ($params as $name => $value) {
                    if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
                        return false;
                    }
                }
            }

            return true;
        }

        return false;
    }

    /**
     * Renders a widget's item.
     * @param string|array $item the item to render.
     * @return string the rendering result.
     * @throws InvalidConfigException
     */
    public function renderItem($item)
    {
        if (is_string($item)) {
            return $item;
        }
        if (!isset($item['label'])) {
            throw new InvalidConfigException("The 'label' option is required.");
        }
        $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
        $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
        $options = ArrayHelper::getValue($item, 'options', []);
        $items = ArrayHelper::getValue($item, 'items');
        $url = ArrayHelper::getValue($item, 'url', '#');
        $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []);

        if (isset($item['active'])) {
            $active = ArrayHelper::remove($item, 'active', false);
        } else {
            $active = $this->isItemActive($item);
        }

        if (empty($items)) {
            $items = '';
        } else {
            //$linkOptions['data-toggle'] = 'dropdown';
            //Html::addCssClass($options, ['widget' => 'dropdown']);
            //Html::addCssClass($linkOptions, ['widget' => 'dropdown-toggle']);
            if ($this->dropDownCaret !== '') {
                $label .= ' ' . $this->dropDownCaret;
            }
            if (is_array($items)) {
                if ($this->activateItems) {
                    $items = $this->isChildActive($items, $active);
                }
                $items = $this->renderChildren($items);
                if(empty($items)) return null;
            }
        }

        if ($this->activateItems && $active) {
            Html::addCssClass($options, 'active');
        }

        return Html::tag('li', Html::a($label, $url, $linkOptions) . $items, $options);
    }

    public function renderChildren($children)
    {
        $items = [];
        foreach ($children as $i => $item) {
            if (isset($item['visible']) && !$item['visible']) {
                continue;
            }
            $items[] = $this->renderItem($item);
        }

        if(empty($items)) return null;

        return Html::tag('ul', implode("\n", $items), $this->childOptions);
    }
}

在权限文件去除

[
    'label' => '<i class="fa fa-edit"></i><span class="nav-label">权限管理</span>',
    'items' => [
        [
            'label' => '账号管理', 'url' => ['/administrator/list'],
            'visible' => Yii::$app->user->can('administrator/list')
        ],
        [
            'label' => '角色管理', 'url' => ['/role/list'],
            'visible' => Yii::$app->user->can('role/list')
        ],
    ],
],

© 著作权归作者所有

共有 人打赏支持
botkenni
粉丝 17
博文 405
码字总数 433796
作品 0
西城
程序员
私信 提问
yii2.0有什么好的开源cms么?

之前用thinkphp,现在想学下yii,不过听说yii2.0跟之前的版本差别很大,就不想学旧的了,想找款带前后台基于yii2.0的系统来学习下,有推荐的么?

david55
2014/10/29
7.9K
8
FastAdmin 极速后台管理框架 1.0.0.20181127_beta 发布

FastAdmin 极速后台管理框架 1.0.0.20181127_beta 新增前台会员Money字段和余额日志表 新增插件配置温馨提示的功能 新增后台登录入口为默认时的安全提示 新增余额增减的静态方法 优化前台默认...

F4NNIU
11/27
2.2K
12
Jflyfox 2.5 更新发布,jfinal+beetl博客

本人的个人博客项目(http://www.jflyfox.com/)功能已基本搭建完成。 现在这个项目断断续续做一年多的时间了,基本功能也已经完成,欢迎大家试用,多提出宝贵意见。 本次更新说明 1)加入文章...

Fly的狐狸
2015/05/21
1K
8
晚黎/iDashboard

iDashboard - Laravel5.3基本的权限管理系统 当前分支为Laravel版本~,Vue2.0版本戳这里 ,Vue2.0只完成了部分,用户管理,权限管理以及角色管理,其他的都还没有做。本人时间有限,重复的增删...

晚黎
2016/11/07
0
0
PHPSHE v1.4 版发布,B2C 商城系统

【PHPSHE基本资料】: 当前版本:PHPSHE B2C商城系统v1.4(build 20150515 UTF8) 演示网站:http://www.phpshe.com/demo/phpshe 【PHPSHE系统简介】: PHPSHE商城系统是将商品管理、品牌管理、规...

koyshe
2015/05/15
7.3K
16

没有更多内容

加载失败,请刷新页面

加载更多

正则表达式匹配不包含

^((?!xxx).)*$

安小乐
8分钟前
1
0
python Windows tkinter应用开发3 列出目录的所有文件

在本章中,我们将编写程序来执行此操作。 1)选择文件夹。 2)在UI的标签部分打印该文件夹中的所有文件名(带文件扩展名)。 首先,修改selectFile函数以打开文件夹。主文件如下: from tki...

python测试开发人工智能安全
9分钟前
1
0
使用Laya引擎开发微信小游戏(上)

  使用一个简单的游戏开发示例,由浅入深,介绍了如何用Laya引擎开发微信小游戏。      img      作者:马晓东,腾讯前端高级工程师。      微信小游戏的推出也快一年时间了,...

SEOwhywhy
14分钟前
1
0
react程序开发问题记录

1、webpack.config.dev.js文件的publicpath配置

teamlog
27分钟前
2
0
javascript 值转换为布尔值

任意javascript 的值都可以转换为布尔值。 特别是在 if() 等判断中使用的时候: 下面这些值会被转换为 false undefined , null , 0 , -0 , NaN , "" 空字符串 来自 JavaScript 权威指南 书籍...

之渊
30分钟前
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部