How do I use datasources in CakePHP 2?

2019-07-21 08:47发布

问题:

My MongoDB datasource is located in plugins/mongodb.

According to the new class loader in 2.0 I should do this:

App::uses('MongodbSource', 'Mongodb.Model/Datasource');

But how do I initiate it?

Or is it best practice to use the ConnectionManager? If so, how do I import it?

回答1:

If you WANT to use your way and loading this datasource "by hand" and not like Matt said, you would initiate it like this:

# /path/to/your/datasource
class MongoDbDatasource {...} //check how this class is named!

Within your file where you load it you can do this:

App::uses('MongodbSource', 'Mongodb.Model/Datasource');
$mongodb = new MongoDbDatasource();

But as said, the databsae configuration would be the better way:

public $default = array(
    'datasource' => 'Mongodb.MongodbSource',
    'database' => 'mydbname',
    'host' => 'yourhost',
    'port' => 'yourport',
    'login' => 'yourlogin',
    'password' => 'yourpassword'
);

Now you just have so add CakePlugin::load('Mongodb'); to your bootstrap.php so your plugin will be loaded.



回答2:

You need to tell your database configuration which datasource to use:

class DATABASE_CONFIG {

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'user',
    'password' => 'password',
    'database' => 'database_name',
    'prefix' => '',
);

}