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

How to access Phalcon from a single PHP file

I have a project build by Phalcon.

Everything is ok. Now I want to use Gearman in my project to do some tasks in background (sending email, process image, convert video,...)

I have a file worker.php like this:

<?php

$worker = new GearmanWorker();
$worker->addServer();

$worker->addFunction("send_email", function(GearmanJob $job) {
    $email = $job->workload();
    echo "Sending email: $email \n";
    mail($email, "test gearman", "this is a test from gearman");
    $job->sendStatus(1, 1);
});

while ($worker->work());

In function send_email, how to access Phalcon like this (while worker.php is a single file, outside from the project)

<?php

$worker = new GearmanWorker();
$worker->addServer();

$worker->addFunction("send_email", function(GearmanJob $job) {

    //accss Phalcon model
    $user = User::findFirstById();
    $email = $user->email;

    echo "Sending email: $email \n";
    mail($email, "test gearman", "this is a test from gearman");
    $job->sendStatus(1, 1);
});

while ($worker->work());


5.2k
Accepted
answer
edited Oct '14

Hi, example

$worker = new GearmanWorker();
$worker->addServer();

$application = new \Phalcon\Application();

or $di

$di = new MyDi();

$worker->addFunction("send_email", function(GearmanJob $job) use(&$application, &$di) {
    //now you get this an application object!

    //now you get this an Di object!

    //ORM is a static case, you can use it without any external code as I know

    //accss Phalcon model
    $user = User::findFirstById();
    $email = $user->email;

    echo "Sending email: $email \n";
    mail($email, "test gearman", "this is a test from gearman");
    $job->sendStatus(1, 1);
});


6.6k
edited Oct '14

Include an autoloader (to include User model) and your Di with database connection, models manager, etc. (e.g. the FactoryDefault Di with custom configuration) and you can use Phalcon like you've written it.

@Дмитрий Пацура: Your solution works. I forgot the magic method use() in the function. It's very helpful.