简体   繁体   中英

What is the safest way to share objects PHP

I have to share an instance of a config object in PHP. This object contains db username and db password. The db user can change. So I have to share te object instance.

Example.

Default db user is 'default'. default has only rights to SELECT data from db.

When website user logges in on website as admin, db user has to change to 'admin'. admin has rights to SELECT, UPDATE, DELETE etc.

When web user logges in as a normal user, db user has to change to 'normal' normal has rights as SELECT, UPDATE etc.

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");
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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