×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: PHP
Posted by: Roman Ignatov
Added: Nov 22, 2016 4:27 PM
Modified: Nov 22, 2016 4:28 PM
Views: 21
Tags: phalcon
For more details check this page
https://docs.phalconphp.com/en/latest/reference/models.html#setting-multiple-databases
  1. <?php
  2.  
  3. // First of all connections have to be configured in the configuration
  4. // This service returns a MySQL database
  5. $di->set('dbMysql', function () {
  6.     return new MysqlPdo(
  7.         array(
  8.             "host"     => "localhost",
  9.             "username" => "root",
  10.             "password" => "secret",
  11.             "dbname"   => "invo"
  12.         )
  13.     );
  14. });
  15.  
  16. // This service returns a PostgreSQL database
  17. $di->set('dbPostgres', function () {
  18.     return new PostgreSQLPdo(
  19.         array(
  20.             "host"     => "localhost",
  21.             "username" => "postgres",
  22.             "password" => "",
  23.             "dbname"   => "invo"
  24.         )
  25.     );
  26. });
  27.  
  28. ?>
  29.  
  30.  
  31.  
  32. <?php
  33. /**
  34. * then on the model level could be used different DB connections
  35. *
  36. */
  37.  
  38.  
  39. class Robots extends Model
  40. {
  41.     public function initialize()
  42.     {
  43.         $this->setConnectionService('dbPostgres');
  44.     }
  45. }
  46.  
  47. // or like this
  48.  
  49. use Phalcon\Mvc\Model;
  50.  
  51. class Robots extends Model
  52. {
  53.     public function initialize()
  54.     {
  55.         $this->setReadConnectionService('dbSlave');
  56.         $this->setWriteConnectionService('dbMaster');
  57.     }
  58. }
  59.  
  60.  
  61. <?php
  62.  
  63. /**
  64. * Another very custom connection selection
  65. * By simply override the getWriteConnection in a model you can dynamically change the connection used to write data
  66. */
  67.  
  68. class Robots extends Phalcon\Mvc\Model
  69. {
  70.     public static function getWriteConnection()
  71.     {
  72.         if ($this->shardKey == 'abcd') {
  73.             return $this->getDI()->get('dbMysql1');
  74.         }
  75.         if ($this->shardKey == 'efgh') {
  76.             return $this->getDI()->get('dbMysql2');
  77.         }
  78.         return $this->getDI()->get('dbMysql3');
  79.     }
  80. }
  81.  
  82. ?>