Laravel 队列错误 - “脚本尝试调用不完整对象上的方法”

问题描述 投票:0回答:1

当我尝试使用 Laravel 队列分派作业时,我的 Laravel 应用程序遇到了问题。我收到的错误消息是:

Error: The script tried to call a method on an incomplete object. Please ensure that the class definition "App\Jobs\SeedingCustomerData" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide an autoloader to load the class definition in /var/www/html/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php:117
Stack trace:
#0 /var/www/html/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(117): method_exists()
#1 /var/www/html/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(70): Illuminate\Queue\CallQueuedHandler->dispatchThroughMiddleware()
#2 /var/www/html/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(98): Illuminate\Queue\CallQueuedHandler->call()
#3 /var/www/html/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(428): Illuminate\Queue\Jobs\Job->fire()
#4 /var/www/html/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(378): Illuminate\Queue\Worker->process()
#5 /var/www/html/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(172): Illuminate\Queue\Worker->runJob()
#6 /var/www/html/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(117): Illuminate\Queue\Worker->daemon()
#7 /var/www/html/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(101): Illuminate\Queue\Console\WorkCommand->runWorker()
#8 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\Queue\Console\WorkCommand->handle()
#9 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Util.php(40): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#10 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\Container\Util::unwrapIfClosure()
#11 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\Container\BoundMethod::callBoundMethod()
#12 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(653): Illuminate\Container\BoundMethod::call()
#13 /var/www/html/vendor/laravel/framework/src/Illuminate/Console/Command.php(136): Illuminate\Container\Container->call()
#14 /var/www/html/vendor/symfony/console/Command/Command.php(298): Illuminate\Console\Command->execute()
#15 /var/www/html/vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Symfony\Component\Console\Command\Command->run()
#16 /var/www/html/vendor/symfony/console/Application.php(1040): Illuminate\Console\Command->run()
#17 /var/www/html/vendor/symfony/console/Application.php(301): Symfony\Component\Console\Application->doRunCommand()
#18 /var/www/html/vendor/symfony/console/Application.php(171): Symfony\Component\Console\Application->doRun()
#19 /var/www/html/vendor/laravel/framework/src/Illuminate/Console/Application.php(94): Symfony\Component\Console\Application->run()
#20 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\Console\Application->run()
#21 /var/www/html/artisan(37): Illuminate\Foundation\Console\Kernel->handle()
#22 {main}

这是我的控制器中的相关代码

  public function processing_customer_subscription(Request $request)
{
  try {
    $token = $this->generateSeedingToken();
    $customer = Customer::where('email', $request->input('email'))->orWhere('id', $request->input('user_id'))->first();
    if ($customer == null)
      throw new \Exception('data customer tidak ditemukan', 422);

    $module = Module::where('code', $request->input('code_module'))->first();
    $package = Package::where([
      'code' => $request->input('code_package'),
      'module_id' => $module->id
    ])->first();

    $check_sub = CustomerSubscription::where([
      'billing_number' => $request->input('billing_number'),
      'customer_id' => $customer->id
    ])->count();

    if ($check_sub > 0) {
      // TODO
      $subs = CustomerSubscription::where('billing_number', $request->input('billing_number'))->first();
      $this->response['data'] = $subs;
      $this->response['msg']  = 'berhasil';
    } else {
      $db = DB::transaction(function () use ($request, $customer, $module, $package, $token) {
        // create subscription data
        $subs = new CustomerSubscription();
        $subs->id = $this->generateRandomUuid();
        $subs->customer_id = $customer->id;
        $subs->module_id = $module->id;
        $subs->package_id = $package->id;
        $subs->billing_number = $request->input('billing_number');
        $subs->start_date = $request->input('start_date');
        $subs->end_date = $request->input('end_date');
        $subs->max_user = $package->max_user;
        $subs->max_data = $package->max_data;
        $subs->contract_value = $request->input('total_price');
        $subs->payment_status = 'PAID';
        $subs->status = 'ACTIVE';
        $subs->save();

        return $subs;
      });

      SeedingCustomerData::dispatch($customer->code, $token)->afterCommit();
      $this->response['data'] = $db;
      $this->response['msg']  = 'berhasil';
    }

    return $this->response;

  } catch (\Throwable $th) {
    $errorCode = ($th->getCode() > 99 && $th->getCode() < 600) ? $th->getCode() : 500;
    throw new \Exception($th->getMessage(), $errorCode);
  }
}

在我的工作课程中(SeedingCustomerData):

class SeedingCustomerData implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, Common;
    private $code;
    private $token;

    public function __construct($code, $token)
    {
        $this->code = $code;
        $this->token = $token;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        set_time_limit(160);
        $customer = Customer::select('id','name','code','email','phone','password')->where('code', $this->code)->first();
       
        $dataToSeed = [
            'charter_categories' => CharterCategory::all(),
            'charter_delivery_statuses' => CharterDeliveryStatus::all(),
            'charter_value_categories' => CharterValueCategory::all(),
            'category_file' => CategoryFile::all(),
            'cost_resources' => CostResource::all(),
            'charter_tags' => CharterTag::all(),
            'charter_type_groups' => CharterGroupType::all(),
            'currencies' => Currency::all(),
            'partners' => Partner::all(),
            'pay_types' => PaymentType::all(),
            'risk_categories' => RiskCategory::all(),
            'risk_impacts' => RiskImpact::all(),
            'risk_statuses' => RiskStatus::all(),
            'stackholder_types' => StackholderType::all()
            // 'Language' => Language::all(),
            // 'Theme' => Theme::all()
        ];

        $dbTenant = DB::connection('tenant_master');

        try {
            $dbTenant->beginTransaction();

            foreach ($dataToSeed as $modelName => $data) {
                $this->seedData($dbTenant, $modelName, $data, $customer->code);
            }

            $dbTenant->commit();

            SeedingStatus::on('pgsql')->where('token', $this->token)
                ->update([
                    'seeding_end_time' => Carbon::now()->format('Y-m-d H:i:s'),
                    'is_successful' => true,
                ]);
        } catch (\Throwable $th) {
            $dbTenant->rollback();
        }
    }

    private function seedData($db, $modelName, $data, $tenantCode)
    {
        if (count($data) > 0) {
            $data->each(function ($record) use ($db, $modelName, $tenantCode) {
                unset($record->deleted_at);
                unset($record->id);
                $record->tenant_id = $tenantCode;
                $record->id = $this->generateRandomUuid();

                $db->table(strtolower($modelName))->updateOrInsert(
                    ['tenant_id' => $tenantCode],
                    $record->toArray()
                );
            });
        }
    }
}

我尝试了多种方法来解决此问题,包括检查类是否已正确自动加载并确保加载了必要的依赖项。但是,我仍然遇到这个错误。

有人可以帮助我了解可能导致此错误的原因以及如何修复它吗?任何见解或建议将不胜感激。

php laravel queue jobs
1个回答
0
投票

作业序列化:

如果您使用 Eloquent 模型或自定义类来调度作业,请确保 这些模型可以正确序列化。您可以通过确保您的模型来检查这一点 实现了 Serialized 接口。

class MyModel extends Model implements Serializable
{
    // ... Model code ...

    public function serialize()
    {
        return serialize($this->attributes);
    }

    public function unserialize($data)
    {
        $this->attributes = unserialize($data);
    }
}

运行以下命令

php artisan 缓存:清除 php artisanconfing:缓存 php artisanconfing:清除 php artisan 优化:清除 作曲家转储自动加载

要解决此问题,您应该确保 Customer 和所有其他的类定义 SeedingCustomerData 作业中使用的模型类在作业启动时可用。 unserialized。您可以通过将这些类添加到作业类的 use 语句中来完成此操作 这样 Laravel 在反序列化作业时就能意识到它们。

以下是修改 SeedingCustomerData 作业类以包含必要的 use 语句的方法:

use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Customer;  // Add the necessary use statement for the Customer model
use App\CharterCategory; // Include use statements for all other models used in the job

class SeedingCustomerData implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, Common;
    
    // ... Rest of your class code ...

    public function handle()
    {
        // ... Rest of your handle method ...

        $customer = Customer::select('id','name','code','email','phone','password')->where('code', $this->code)->first();
       
        // ... Rest of your handle method ...

        foreach ($dataToSeed as $modelName => $data) {
            $this->seedData($dbTenant, $modelName, $data, $customer->code);
        }

        // ... Rest of your handle method ...
    }

    // ... Rest of your class code ...
}

确保您已为 SeedingCustomerData 作业中使用的所有模型类添加 use 语句。 这将确保 Laravel 可以在作业中正确反序列化和使用这些类。

© www.soinside.com 2019 - 2024. All rights reserved.