0

I working on a project where user register and get a free online shop using CakePHP v2.6.5. I'm using shared hosting so i can't create Mysql database for them, So I use sqlite instead. Because I need to use it with Mobile App too. In my code I dynamically create sqlite file for user after their register. But I don't know how to change database path in CakePHP. All I know is CakePHP use config in config/database.php file, but i can't init it dynamically.

In my config/database.php file:

public $sqliteDB = array(
    'datasource' => 'Database/Sqlite',
    'persistent' => false,
    //'database'=>'',
    'prefix' => '',
    'encoding' => 'utf8'
);

I trying to follow these link: CakePHP switch database (using same datasource) on the fly? and this link Cakephp can't change database on-the-fly, but I got nothing.

Community
  • 1
  • 1

1 Answers1

0

I figure out how to do it by create ConnectionManager on the fly in __construct() method of model. But I use it with multi table so here my code

In AppModel:

public function connectSqlite()
{
    App::uses('CakeSession', 'Model/Datasource');
    $shop = CakeSession::read('SHOP');    //just read Session for shop's name, because i create a directory and store sqlite in it. Directory name base on shop name that user defined when user registerd.
    if($shop)
    {
        $dbName=FILES_URL.'shops'.DS.$shop['name'].DS.'database'.DS.'database.sqlite';    //Sqlite file path
        $sqliteDB = array(
            // Set correct database name
            'datasource' => 'Database/Sqlite',
            'persistent' => false,
            'database'=>$dbName,
            'prefix' => '',
            'encoding' => 'utf8'
        );
        // Add new config to registry
        ConnectionManager::create($dbName, $sqliteDB);    //create ConnectionManager and return it to derived class.
        // Point model to new config
        return $dbName;
    }
}

In Product Model:

public function __construct($id = false, $table = null, $ds = null)
{
    $dbName=parent::connectSqlite();
    if($dbName){
        $this->useDbConfig=$dbName;
    }
    parent::__construct($id, $table, $ds);
}

Hope this can help!