基于Zend Framework中的现有连接创建新的数据库连接

时间:2012-05-16 10:59:03

标签: php zend-framework pcntl

我有一个使用Zend Framework的CLI脚本并分叉子进程。 当我从CLI启动它时,它运行良好但是当我从bash脚本启动它时,当bash脚本结束时,db连接将被关闭。

我想我需要给孩子一个新的数据库连接到同一个数据库。 不幸的是,最初创建连接的方式对我来说太过神秘了,所以我想基于现有的连接创建新的连接。我怎么能这样做?

这是它在Bootstrap中创建的方式以及我以后如何访问它:

$resource = $this->getPluginResource ( 'db' );
$db = $resource->getDbAdapter ();
Zend_Registry::getInstance ()->dbAdapter = $db;    

$this->db = Zend_Registry::get ( 'dbAdapter' );

这就是我想使用新连接的地方:

public function start_daemon($worker) {
    if (file_exists ( $this->get_pidfile ( $worker ) ))
        die ( 'process is already running - process pidfile already exists -> ' . $this->get_pidfile ( $worker ) . "\n" );
    $cmd = 'php -f ' . __FILE__ . ' process';
    if ($this->is_win) {
        $WshShell = new COM ( "WScript.Shell" );
        $oExec = $WshShell->Run ( "$cmd /C dir /S %windir%", 0, false );
        exec ( 'TASKLIST /NH /FO "CSV" /FI "imagename eq php.exe" /FI "cputime eq 00:00:00"', $output );
        $output = explode ( '","', $output [0] );
        $pid = $output [1];
        file_put_contents ( $this->get_pidfile ( $worker ), $pid );
        echo ('JobQue daemon started with pidfile:' . $this->get_pidfile ( $worker ) . "\n");
    } else {
        $PID = pcntl_fork ();
        if ($PID) {
            file_put_contents ( $this->get_pidfile ( $worker ), $PID );
            echo ('JobQue daemon started with pidfile:' . $this->get_pidfile ( $worker ) . "\n");                               
            exit (); // kill parent
        }
        //!!Need to create a new db connection here
        //to make sure the child will have one
        //when the parent exits
        posix_setsid (); // become session leader
        chdir ( "/" );
        umask ( 0 ); // clear umask
        $this->proc_nice ( 19 );
        $this->process_jobs ();
    }
}

1 个答案:

答案 0 :(得分:0)

您可以像这样访问

public function start_daemon($worker) {

    $db = Zend_Registry::get ( 'dbAdapter' );
    //do database operations with db object

用于新连接

//if config is stored in registry,
$config= Zend_Registry::get ( 'config' );
$db = Zend_Db::factory($config['resources']['db']['adapter'], $config['resources']['db']['params']);

OR 

$db = Zend_Db::factory('Pdo_Mysql', array(
            'host'     => 'hostname',
            'username' => 'xxxxxxx',
            'password' => 'xxxxxxxx',
            'dbname'   => 'xxxxxxxxx'
        ));



 //set as default adapter
    Zend_Db_Table_Abstract::setDefaultAdapter($db);