简体   繁体   English

共享对象最安全的方法是什么?

[英]What is the safest way to share objects PHP

I have to share an instance of a config object in PHP. 我必须在PHP中共享一个配置对象的实例。 This object contains db username and db password. 该对象包含数据库用户名和数据库密码。 The db user can change. db用户可以更改。 So I have to share te object instance. 因此,我必须共享对象实例。

Example. 例。

Default db user is 'default'. 默认的数据库用户为“默认”。 default has only rights to SELECT data from db. default仅具有从db SELECT数据的权限。

When website user logges in on website as admin, db user has to change to 'admin'. 当网站用户以管理员身份登录网站时,数据库用户必须更改为“ admin”。 admin has rights to SELECT, UPDATE, DELETE etc. 管理员拥有SELECT,UPDATE,DELETE等权限。

When web user logges in as a normal user, db user has to change to 'normal' normal has rights as SELECT, UPDATE etc. 当Web用户以普通用户身份登录时,数据库用户必须更改为“普通”普通用户,并具有SELECT,UPDATE等权限。

I've to share the config instance. 我必须共享配置实例。 What is the safest way to share this object? 共享此对象的最安全方法是什么?

You could make use of the singleton pattern in order to keep one instance accessible from anywhere within your application. 您可以利用单例模式来保持一个实例可以从应用程序中的任何位置访问。

I also suggest you have a singleton as a connection-handler where you can get, set and maintain connections, in which you also store the login credentials. 我还建议您将单例用作连接处理程序,在其中可以获取,设置和维护连接,并在其中存储登录凭据。

Example: 例:

<?php
class ConnectionManager
{
    private $hostname;
    private $username;
    private $password;

    private $connections = array();

    private static $instance = null;

    public static function getInstance ()
    {
        if (self::$instance == null)
            self::$instance = new self();
        return self::$instance;
    }

    private function __construct ()
    {}

    public function newConnection ($name, $database)
    {
        // Connect to database using predefined credentials

        $this->connections[$name] = new PDO();
    }

    public function __get ($name)
    {
        if (!array_key_exists($name, $this->connections))
            die("Could not get connection: $name");

        return $this->connections[$name];
    }
}

// Create a new connection named database1
ConnectionManager::getInstance()->newConnection('database1', 'database_name');

// Load connection database1
ConnectionManager::getInstance()->database1->prepare("SELECT * FROM table");
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM