You have encountered a glitch of ModX, and it took me a long time to solve. ModX does a lot of caching by using hashing and apparently, when multiple connections are made from within one page divided over multiple snippets, this erratic behaviour can be seen. This is most likely very unwanted behaviour, it can be solved easily but gives you terrible headache otherways.
One sympton is that $modx->getObject($classname, $id)
returns null (often).
The solution is very simple:
either use a static class with a single db instance, or
use $modx->setPlaceholder($instance, $tag);
, or a combination.
My solution has been:
class dt__xpdo {
private function __construct() {}
public function __destruct() {
$this->close();
}
static public function db($modx = null) {
if ($modx->getPlaceholder( dt_xpdo ) == ) {
$dt_user = xxxxxxxxx ;
$dt_pw = xxxxxxxxx ;
$dt_host = localhost ;
$dt_dbname = xxxxxxxxx ;
$dt_port = 3306 ;
$dt_dsn = "mysql:host=$dt_host;dbname=$dt_dbname;port=$dt_port;charset=utf8";
$dt_xpdo = new xPDO($dt_dsn, $dt_user, $dt_pw);
$dt_xpdo->setPackage( mymodel , MODX_CORE_PATH. components/mymodel/ . model/ , );
//$modx->log(modX::LOG_LEVEL_DEBUG, mymodel.config.php );
//$modx->log(modX::LOG_LEVEL_DEBUG, Could not addPackage for mymodel! );
$modx->setPlaceholder( dt_xpdo , $dt_xpdo);
}
return $modx->getPlaceholder( dt_xpdo );
}
}
Now you can use in your code:
require_once above.php ;
and use something like
$xpdo = dt__xpdo::db($modx);
and continue flawlessly!