BigDbServer.php

<?php

namespace Tlf;

/**
 *
 */
class BigDbServer {

    /**
     * Databases added to this server.
     *
     * @var array<string, \Tlf\BigDb> where the key comes from `$bigdb->get_db_name()` if not passedd to `addDatabase($db, $db_name)`
     */
    protected array $databases = [];

    /**
     * Add a BigDb database to the server.
     *
     * @param $db a BigDb instance
     */
    public function addDatabase(\Tlf\BigDb $db, ?string $db_name = null){
        if ($db_name==null)$db_name = $db->get_db_name();

        if (isset($this->databases[$db_name])){
            throw new \Exception("Database `$db_name` is already added to this BigDbServer. Pass second paramater $db_name to `addDatabase(\$db, \$db_name)`, to use this database under a non-default name.");
        }
        
        $this->databases[$db_name] = $db;
    }

    /**
     * Get a database
     */
    public function __get(string $prop): \Tlf\BigDb {
        if (!isset($this->databases[$prop])){
            throw new \Exception("Database '$prop' has not been added to this server. Use BigDbServer::dump() for a list of databases.");
        }
        return $this->databases[$prop];
    }

    /**
     * Print information about the server - currently just the databases added.
     */
    public function dump(){
        echo "\n\n\n-----------\n<pre>\n";
        foreach ($this->databases as $name=>$db){
            $class = get_class($db);
            echo "\n- Database '$name' is an instance of $class";
        }


        echo "\n\n</pre>\n-----------\n\n";
    }
}