Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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());


4.0k
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);
});


4.2k
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.