设计模式之享元模式

<?php
// 享元模式: 简单来说就是减少程序运行中产生的细粒度对象
// 比如权限控制中的权限对象的产生, 可以将不变且重复出现的数据分离出来共享, 即 "入口"=>"权限",如果在内存中有,则返回这个唯一标识码("入口"=>"权限")所标识的对象


class AuthFlyWeightFactory
{
    protected static $ins;
    protected $authList = [];

    protected function __construct(){
        $this->authList = array();
    }

    public function getIns()
    {
        if (!self::$ins instanceof self) {
            self::$ins = new self();
        }
        return self::$ins;
    }

    public function getAuthFlyWeight($authCondition)
    {
        if ( !isset($this->authList[$authCondition]) ) {
            $this->authList[$authCondition] = new AuthFlyWeight($authCondition);
        }

        return $this->authList[$authCondition];
    }
}

class AuthFlyWeight
{
    public function __construct($authCondition)
    {
        list($this->entry,$this->permit) = explode(',',$authCondition);
    }

    public function match($entry,$permit)
    {
        return $this->entry == $entry && $this->permit == $permit;
    }
}

class SecurityMgr 
{
    protected $userData;
    protected static $ins;
    protected $userAuth;

    public function getIns()
    {
        if (!self::$ins instanceof self) {
            self::$ins = new self();
        }
        return self::$ins;
    }    

    protected function __construct()
    {
        // 从数据库获取所有用户权限信息
        $this->userData = array(
            ['tom','username','update'],
            ['jay','nickname','del'],
            ['tom','username','update'],
        );
    }

    public function login($username)
    {
        if ( !isset($this->userAuth[$username]) ) {
            $this->userAuth[$username] = $this->queryUser($username);
        }
    }

    public function queryUser($username)
    {
        $col = array();
        foreach ($this->userData as $user) {
            if ($username == $user[0]) {
                $col[] = AuthFlyWeightFactory::getIns()->getAuthFlyWeight($user[1] . ',' . $user[2]);
            }
        }
        return $col;
    }

    public function hasPermit($username,$entry,$permit)
    {
        if ( empty($this->userAuth[$username]) ) {
            return false;
        }

        foreach ($this->userAuth[$username] as $authFlyWeight) {
            if ($authFlyWeight->match($entry,$permit)) {
                return true;
            }
        }

        return false;
    }
}

$mgr = SecurityMgr::getIns();
$mgr->login("tom");
$mgr->login("jay");
var_dump($mgr->hasPermit("tom", "username", "update"));
var_dump($mgr->hasPermit("jay", "nickname", "del"));

标签: none