We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Models in Namespaces and multiple databases

model UsersNs1.php


namespace Ns1;

class Users extends \Phalcon\Mvc\Model
{

    /**
     * @var integer
     *
     */
    public $id;

    /**
     * @var integer
     *
     */
    public $ns1;

    public function initialize()
    {
        $this->setConnectionService('db_1');
    }

}

model UsersNs2.php


namespace Ns2;

class Users extends \Phalcon\Mvc\Model
{

    /**
     * @var integer
     *
     */
    public $id;

    /**
     * @var integer
     *
     */
    public $ns2;

    public function initialize()
    {
        $this->setConnectionService('db_2');
    }

}

script:

<?php

echo PHP_EOL;

require_once 'models/UsersNs1.php';
require_once 'models/UsersNs2.php';

$di = new Phalcon\DI();

$di->set('modelsManager' , new \Phalcon\Mvc\Model\Manager());
$di->set('modelsMetadata' , new \Phalcon\Mvc\Model\Metadata\Memory());

$di->set('db_1' , new \Phalcon\Db\Adapter\Pdo\Mysql(array( "host" => 'localhost' , "username" => 'root' , "password" => '' , "dbname" => 'db_1' )));
$di->set('db_2' , new \Phalcon\Db\Adapter\Pdo\Mysql(array( "host" => 'localhost' , "username" => 'root' , "password" => '' , "dbname" => 'db_2' )));

echo 'model 1'.PHP_EOL;
$ns1 = new \Ns1\Users;
print_r($ns1->toArray());

echo 'model 2'.PHP_EOL;
$ns2 = new \Ns2\Users;
print_r($ns2->toArray());

```php

result:
```code
model 1
Array
(
    [id] => 
    [ns1] => 
)
model 2
Array
(
    [id] => 
    [ns1] => 
)

interchange

echo 'model 2'.PHP_EOL;
$ns2 = new \Ns2\Users;
print_r($ns2->toArray());

echo 'model 1'.PHP_EOL;
$ns1 = new \Ns1\Users;
print_r($ns1->toArray());

result:

model 2
Array
(
    [id] => 
    [ns2] => 
)
model 1
Array
(
    [id] => 
    [ns2] => 
)


98.9k

Hi @boston, is this a bug report? It's already reported on Github https://github.com/phalcon/cphalcon/issues/501, thanks