使用laravel中的对象集合

使用laravel中的对象集合,laravel,collections,Laravel,Collections,正在尝试使用对象集合。 该系列不是雄辩的,而是手工制作的illumb\Support\collection 如果我对对象集合的理解是正确的,那么我不能使用大多数方法,只能使用那些可以使用回调的方法 因此,我收集了一些对象: 下面是代码($country='rusia'): 我希望$filtered只包含一个元素,返回true(在我们的例子中是俄罗斯) 但是我没有用它,而是用同样的3个元素的集合 下面是其他类,以确保它们与集合相关 use App\Services\Taxes\DataSourc

正在尝试使用对象集合。
该系列不是雄辩的,而是手工制作的
illumb\Support\collection

如果我对对象集合的理解是正确的,那么我不能使用大多数方法,只能使用那些可以使用回调的方法

因此,我收集了一些对象:

下面是代码($country='rusia'):

我希望
$filtered
只包含一个元素,返回
true
(在我们的例子中是俄罗斯) 但是我没有用它,而是用同样的3个元素的集合

下面是其他类,以确保它们与集合相关

use App\Services\Taxes\DataSourceInterface;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

abstract class JsonModel extends Collection implements DataSourceInterface
{
    public function __construct()
    {
        parent::__construct($this->readDataFile(env('JSON_DATA_PATH')));
    }

    protected function readDataFile(string $path): array
    {
        $disk = Storage::disk('local');

        try {
            $dataObj = json_decode($disk->get($path), false, 10, JSON_THROW_ON_ERROR);
            return $this->loadData($dataObj);
        } catch (FileNotFoundException $e) {
            Log::error('Storage ' . $e->getMessage() . ' was not found');
        } catch (\JsonException $e) {
            Log::error('Json DataFile: ' . $e->getMessage());
        }

        return [];
    }

    abstract protected function loadData(object $dataObject): array;
}

问题出在
newstatic
中,它在laravel方法中使用返回集合实例的方法,事实上我不希望在构造函数中使用数组条目

在空数组和文件读取之间进行选择可以解决此问题

abstract class JsonModel extends Collection implements DataSourceInterface
{
    public function __construct($dataArr = [])
    {
        if(!is_array($dataArr))
           $dataArr = $this->readDataFile(env('JSON_DATA_PATH'));

        parent::__construct($dataArr);
    }

你能在这里发布你的
JsonCountries
课程吗?可能您的
JsonCountries
类没有扩展
Collection
class@aceraven777,我已经用其他课程更新了帖子。这肯定是收集,至少因为我可以使用基本方法,如
$this->countries->first()
dump($this->countries instanceof collection)是真的你可以试试
dd($filtered->all())我试过了,它返回了所有3个条目
class JsonCountries extends JsonModel
{
    public function loadData(object $dataObject): array
    {
        $data = array_filter($dataObject->countries, function ($item){
            unset($item->states);
            return true;
        });

        return $data;
    }
}
abstract class JsonModel extends Collection implements DataSourceInterface
{
    public function __construct($dataArr = [])
    {
        if(!is_array($dataArr))
           $dataArr = $this->readDataFile(env('JSON_DATA_PATH'));

        parent::__construct($dataArr);
    }