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

Accessing global variables inside a class

I would like to create a query outside a class, so that its only created once. Then the class will include it, and just execute it 1000s of times using different bound parameters.

However, I cannot seem to get the classes to find the global query:

<?php
$GLOBAL_QUERY = new Query("SELECT tbl1.*, tbl2.* FROM \App\Models\Table1 AS tbl1
    INNER JOIN \App\Models\Table2 AS tbl2 ON (tbl1.id = tbl2.id) 
    WHERE tbl1.id = :id:", \Phalcon\DI::getDefault());

class UtilityStuff extends Component
{
    function __construct(){
        // this appears to do nothing -- always ends up being NULL
        global $GLOBAL_QUERY;
    }
}

What am I doing wrong? Using the defined model relations isn't an option, it takes way too long and runs way too many queries.

Thanks!



14.9k

Apparently autoloading of classes might just blow my global variables away. In the mean time here's what I've done, seems to work.

$query = new Query("SELECT tbl1.*, tbl2.* FROM \App\Models\Table1 AS tbl1
    INNER JOIN \App\Models\Table2 AS tbl2 ON (tbl1.id = tbl2.id) 
    WHERE tbl1.id = :id:", \Phalcon\DI::getDefault());
\Phalcon\Di::getDefault()->setShared('query_obj', $query);

class UtilityStuff extends Component
{
    function __construct(){
        // now i can access query, and execute it here:
        $result = $this->query_obj->execute(array('id'=>45));
    }
}

Where you are registering you application services try adding the following;

       $di->set('GLOBAL_QUERY', function () {      
            $query = new Query("SELECT tbl1.*, tbl2.* FROM \App\Models\Table1 AS tbl1
            INNER JOIN \App\Models\Table2 AS tbl2 ON (tbl1.id = tbl2.id) 
            WHERE tbl1.id = :id:", \Phalcon\DI::getDefault());
        }, true);

Then in your class

        $this->GLOBAL_QUERY;