在另一个方法中间调用一个方法会阻止设置以下变量 - Laravel 作业

Calling a method in the middle of a another one prevents following variables from being set - Laravel job

我有一个 Laravel 作业,它设置了一些数据,然后使用这些数据在数据库中创建一个条目。数据库 table 中的所有字段都是 NULL 可用的。有 custom_variables 字段 - 使用自定义方法设置 getByPrefix().

MyJob.php

<?php

class MyJob implements ShouldQueue {

    public function __construct($input) {
        $this->input = $input;
    }

    public function handle() {

        $data = $this->getData();

        MyModel::create($data);

    }

    protected function getData() {

        if (isset($this->input['name'])) {
            $data['name'] = $this->input['name'];
        }


        $data['custom_variables'] = $this->getByPrefix('custom-');

        if (isset($this->input['surname'])) {
            $data['surname'] = $this->input['surname'];
        }

        return $data;
    }


    /**
     * Filter the input by the provided prefix 
     * and return matching input data.
     * @return null|string
     */
    protected function getByPrefix($prefix) {

        $this->input= array_filter($this->input, function($k) use ($prefix) {
            return strpos($k, $prefix) !== false;
        }, ARRAY_FILTER_USE_KEY);

        if (count($this->input) === 0) {
            return null;
        }

        $data = array();

        foreach ($this->inputas $k => $v) {
            array_push($data, array($k => $v));
        }

        if (empty($data)) {
            return null;
        }

        return json_encode($data);

    }

}

问题是如果我在中间保持对getByPrefix()的调用,那么$data['surname']的值总是NULL存储记录时,即使输入中存在 surname

当我将对 getByPrefix() 的调用移动到脚本末尾时,$data['surname'] 设置正确。

为什么会这样?是不是因为我可能returnJSON来自getByPrefix() 方法?不这么认为,但谁知道呢。

我尝试将 getByPrefix() 的主体包装在 try-catch 中 - 但没有任何错误,并且 custom_variables 字段始终在数据库中设置。

知道这里会发生什么吗?

更新

示例输入数据:

array(
    'name' => 'John', 
    'surname' => 'Doe', 
    'custom-var' => 'customValue'
)

输出(应用getByPrefix()后):

array(
    'name' => 'John', 
    'custom_variables' => "[{"custom-var":"customValue"}]"
)

是因为这部分:

$this->input= array_filter($this->input, function($k) use ($prefix) {
        return strpos($k, $prefix) !== false;
    }, ARRAY_FILTER_USE_KEY);

您正在过滤您的输入并将结果覆盖到它。尝试使用另一个变量。

 $input= array_filter($this->input, function($k) use ($prefix) {
        return strpos($k, $prefix) !== false;
    }, ARRAY_FILTER_USE_KEY);

你得到 name 而不是 surname 的原因仅仅是因为你在调用方法之前设置了名称,而后者是在之后设置的。