I am working on a project using Yii2 and trying to implement a task queue using the Yii2 Queue extension with the database driver. After installing and setting it up, I am facing a problem I can't seem to solve.
My task queue configuration is as follows:
'bootstrap' => ['log','queue'],
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=lectorum_erp',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'queue' => [
'class' => \yii\queue\db\Queue::class,
'db' => 'db', // DB connection component or its config
'as log' => \yii\queue\LogBehavior::class,
'tableName' => '{{%queue}}', // Table name
'channel' => 'default', // Queue channel key
'mutex' => \yii\mutex\MysqlMutex::class, // Mutex used to sync queries
'strictJobType' => false,
//'serializer' => \yii\queue\serializers\JsonSerializer::class, // change to JSON serializer
],
],
];
I've created a job called TestJob in my application's models folder, which implements JobInterface:
namespace app\models;
use Yii;
use yii\base\BaseObject;
class TestJob extends BaseObject implements \yii\queue\JobInterface
{
public function execute($queue)
{
echo "El trabajo de prueba se ejecutó correctamente.\n";
}
}
`
When trying to execute the job, I get the following error: yii\queue\InvalidJobException: Failed to instantiate component or class "app\models\TestJob". I've checked the class path, the file name, and regenerated the Composer autoloader using composer dump-autoload, but the error persists.
Additionally, if I remove the serializer line in my queue configuration and use PHP's default serialization, I get a different error: yii\queue\InvalidJobException: Job must be a JobInterface instance instead of __PHP_Incomplete_Class.
I have already read through the documentation and compared my configuration to the examples they provide, and I don't see any significant difference. However, the issue persists.
Has anyone faced a similar issue or have any suggestions about what could be causing this?
Thanks in advance for your help.
I'd like to thank everyone who took part in helping me solve my issue, especially those who pointed out the problem was with the namespace of my TestJob class. It turns out that I was using an advanced Yii2 template, where the 'app' namespace isn't defined by default, and that's why I was getting the error.
The solution was to move my TestJob class to the common\models namespace. Before, my TestJob class looked like this:
After moving my class to common\models, it now looks like this:
Then, I simply imported the class in my controller using its new namespace:
With these changes, my issue was solved and the Yii2 queue is now working perfectly in my project with the advanced template. I hope this can also help someone else who encounters the same issue. Thank you again to everyone for your help!