how best to use two databases in cakephp 2.3? - mongodb

I am using two databases in an application that I am creating in cakephp 2.3. A mysql database, which typically configured, and another database nosql (MongoDB), I use this way for example:
$connection = new Mongo('localhost');
$db = $connection->compras;
return $db->anuncios->insert($dados);
can I use this way?
about security ..., what possible problems that you guys realize to use mongo database that way?

You've to setup environment in the app/Config/Core.php file which mean which database you want to use in which mode i.e. Production, Development, staging etc with below
if(env('HTTP_HOST')):
switch (env('HTTP_HOST')) {
case "example.com":
case "www.example.com":
define('DEVELOPMENT_MODE', false); // Suppose you're using production for Mysql databse
break;
case "development.example.com":
define('DEVELOPMENT_MODE', true); // Suppose you're using development for MongoDB
break;
default:
define('DEVELOPMENT_MODE', true);
break;
}
After that you've to use DEVELOPMENT_MODE variable in the app/Config/database.php file as below i.e.
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'db_username',
'password' => 'db_password',
'database' => 'db_name',
//'prefix' => '',
'encoding' => 'utf8',
);
var $mongo = array(
'datasource' => 'mongodb.mongodbSource',
'persistent' => false,
'host' => 'localhost',
'login' => 'db_username',
'password' => 'db_password',
'database' => 'db_name',
//'prefix' => '',
'encoding' => 'utf8',
);
public function __construct() {
if (DEVELOPMENT_MODE) {
$this->default = $this->mongo;
} else {
$this->default = $this->default;
}
}
}
All the above logic are use for Config settings to use through out application.
Now below code is connect Model to mongoDB.
class Test extends AppModel {
var $name = 'test';
var $primaryKey = 'id';
var $useDbConfig = 'mongo'; // setup the mongodb datasource
// Now is model is connected with mongoDB only....
}

Related

mysql connection driver to dockerize the cakephp 1.3 application

.env file
export MYSQL_URL='mysql'
export MYSQL_USERNAME='root'
export MYSQL_PASSWORD=''
database.php file
class DATABASE_CONFIG {
public function __construct(){
$this->default['host'] = getenv('MYSQL_URL');
$this->default['login'] = getenv('MYSQL_USERNAME');
$this->default['password'] = getenv('MYSQL_PASSWORD');
}
var $default = array(
'driver' => 'Cake\Database\Driver\Mysql', // incompatible driver for cakephp 1.3
'persistent' => false,
'host' => '',
'login' => '',
'password' => '',
'database' => 'RP',
'prefix' => '',
//'encoding' => 'utf8',
);
}
Unable to import DataSource class due to incompatible driver for the cake version used
please suggest a compatible mysql connection driver for cakephp 1.3 on docker
CakePHP 1.3 didn't use namespaces. I think you just want 'driver' => 'mysql'.

How to debug eloquent queries executed in Codeigniter

I'm using Eloquent 5.* on my CodeIgniter3.1.1 project, Everything works fine however i want to check the queries executed when a request is processed,
After some googling i came accross Using Eloquent ORM inside CodeIgniter with added Query Logging and having CI Profiler enabled i see "No Queries Executed",
my database.php configuration for Eloquent looks as below
//Eloquent ORM database connection
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection(array(
'driver' => 'mysql',
'dsn' => 'mysql:host=localhost; dbname=communit_iwa_test charset=utf8;',
'host' => $db['default']['hostname'],
'database' => $db['default']['database'],
'username' => $db['default']['username'],
'password' => $db['default']['password'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => $db['default']['dbprefix'],
));
$capsule->setAsGlobal();
$capsule->bootEloquent();
$events = new Illuminate\Events\Dispatcher;
$events->listen('illuminate.query',function($query, $bindings, $time,$name) {
// Format binding data for sql insertion
foreach ($bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else if (is_string($binding)) {
$bindings[$i] = "'$binding'";
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $query);
$query = vsprintf($query, $bindings);
// Add it into CodeIgniter
$db = & get_instance()->db;
$db->query_times[] = $time;
$db->queries[] = $query;
});
$capsule->setEventDispatcher($events);
/* End of file database.php */
/* Location: ./application/config/database.php */
Your Help is appreciated in advance
To view executed eloquent queries usegetQueryLog() method of the classIlluminate\Database\Capsule\Manager;
in short
Include Illuminate\Database\Capsule\Manager class in your controller or model as use Illuminate\Database\Capsule\Manager as Capsule;
use Capsule::getQueryLog() method to view an array of all queries executed in Eloquent ORM

Lumen connecting to multiple databases using DB_ connections in .env - Possible?

I can see how to have multiple connections using a configuration file in app/config/database.php and this is well documented.
Is this the only way or can you also define multiple connections using the .env file?
First, you'll need to configure your connections. You need to create a config directory in your project and add the file config/database.php. Like this:
<?php
return [
'default' => 'mysql',
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'homestead',
'username' => 'root',
'password' => 'secret',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'mysql2' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'homestead2',
'username' => 'root',
'password' => 'secret',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
],
Once you've added your connection configurations, you can access them by getting the database manager object out of the container and calling ->connection('connection_name'). See below for a full example.
<?php
namespace App\Http\Controllers;
use Illuminate\Database\DatabaseManager;
class StatsController extends Controller
{
/**
* #return array
*/
public function getLatest()
{
// Resolve dependencies out of container
/** #var DatabaseManager $db */
$db = app('db');
$database1 = $db->connection('mysql');
$database2 = $db->connection('mysql2');
// Look up 3 newest users and 3 newest blog posts
$threeNewestUsers = $database1->select("SELECT * FROM users ORDER BY created_at DESC LIMIT 3");
$threeLatestPosts = $database2->select("SELECT * FROM blog_posts ORDER BY created_at DESC LIMIT 3");
return [
"new_users" => $threeNewestUsers,
"new_posts" => $threeLatestPosts,
];
}
}
http://andyfleming.com/configuring-multiple-database-connections-in-lumen-without-facades/

Connect With PostgreSQL in Phalcon Framework

Phalcon is not able to connect to postgrsql. Here are my settings in config.php
return new \Phalcon\Config(array(
'database' => array(
'adapter' => 'Postgresql',
'host' => 'localhost',
'username' => 'postgres',
'password' => 'root',
'dbname' => 'mydb',
'charset' => 'utf8',
),
'application' => array(
'controllersDir' => __DIR__ . '/../../app/controllers/',
'modelsDir' => __DIR__ . '/../../app/models/',
'viewsDir' => __DIR__ . '/../../app/views/',
'pluginsDir' => __DIR__ . '/../../app/plugins/',
'libraryDir' => __DIR__ . '/../../app/library/',
'cacheDir' => __DIR__ . '/../../app/cache/',
'baseUri' => '/test/',
)
));
Page is blank showing no errors.
DI service implementation
use Phalcon\Db\Adapter\Pdo\Postgresql as DbAdapter;
$di->set('db', function () use ($config) {
return new DbAdapter(array(
'host' => $config->database->host,
'username' => $config->database->username,
'password' => $config->database->password,
'dbname' => $config->database->dbname,
"charset" => $config->database->charset
));
});
There is no port in db connection array you used. Default postgresql port is 5432. so use this in your db connection and try to pass array directly to postgresql adapter constructor.
or
install postgres pdo /php pdo again.
I think that code is fine.
I was working a project where i had to use MySQL and PostGres.I connected my Postgresdb by following-
Below default 'db' connection string i wrote the following code inside services.php-
$di->setShared('pgphalcon', function () {
$config = $this->getConfig();
$adaptar = "PostgreSQL";
$class = 'Phalcon\Db\Adapter\Pdo\\' . $adaptar;
$params = [
'host' => "localhost",
'port' => "5432", // for localhost no need to put this line unless u change the port
'username' => "postgres",
'password' => "12345",
'dbname' => "phalcon",
];
$connection = new $class($params);
return $connection;
});
Then your controller function
do the following-
public function yourcontrollernameAction()
{
$con = $this->di->get('pghalcon');
$post = $con->fetchOne("SELECT * FROM blog ORDER BY id DESC LIMIT 1", Phalcon\Db::FETCH_ASSOC);
$this->view->data= $post;
}
For better Understanding I'd like to suggest visit this url
One thing to clarify- I was failed to do db operation by Model for PostGreSQL. That's why I used this way.

how to connect to the database in zend with dsn line

zend framework 1.x
how to receive zend db_adapter and connect to mysql having dsn like
mysql://john:pass#localhost:3306/my_db
previously was always using this way:
$connectParams = array('dbname' => MY_DB,
'password' => MY_PASS,
'username' => MY_USER,
'host' => MY_HOST,
'slave' => array(),
'maxQueryAllowedTime' => 500,
'logQueries' => false);
return new \Db_Adapter_Pdo_Mysqlreplicator($connectParams);
sure i can parse dsn and use usual way, just curious if i can use DSN directly, coz PDO can use it but i cant find how to use it through Zend Db_Adapter
If you are using ZendFramework 1.x ->Try this:-
$config = array('dbname' => 'yourDbName',
'password' => 'yourpassword',
'username' => 'root',
'host' => 'localhost',
'slave' => array(),
'maxQueryAllowedTime' => 500,
'logQueries' => false);
$adapter = new Zend_Db_Adapter_Mysqli($config);
if ($config) {
echo ' connected';
}