Question

I have a CLI script that uses Zend Framework and forks a child process. It works well when I start it from CLI but when I start it from a bash script the db connection is closed when the bash script ends.

I think I need to give the child a new db connection to the same database. Unfortunately the way the connection is originally created is too misterious to me, so I would like to create the new connection based on the existing. How can I do that?

This is how its created in the Bootstrap and how I access it later:

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

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

And this is where I would like to use the new connection:

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 ();
    }
}
Was it helpful?

Solution

You can access like this

public function start_daemon($worker) {

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

For new connection

//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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top