webparking/laravel-type-safe-collection

This package provides type-safe extension of the laravel collection, forcing a single type of object.
8,240 37
Install
composer require webparking/laravel-type-safe-collection
Latest Version:1.1.0
PHP:>=7.1.0
License:MIT
Last Updated:Sep 10, 2020
Links: GitHub  ·  Packagist
Maintainer: crashkonijn

PHP is getting more mature and allows us to program strong typed in new ways with each new version, however we still lack the option to have generic lists/arrays. This package aims to provide such a thing in the meantime.

The TypeSafeCollection provided by this package will make sure that any object within it is the object you expect.

Installation

Add this package to composer.

composer require webparking/laravel-type-safe-collection

Usage

/**
 * @method \ArrayIterator|User[] getIterator()
 * @method User|null             first()
 */
class UserCollection extends TypeSafeCollection
{
    protected $type = User::class;
}
class User extends Model
{
    public function newCollection(array $models = []): UserCollection
    {
        return new UserCollection($models);
    }
}

All queries on User that would result in a Collection will now result in a UserCollection.

get_class(User::all()) // UserCollection
get_class(User::where('type', '=', 'admin')->get()) // UserCollection
get_class(User::where('id', '=', 1)->first()) // User

Licence and Postcardware

This software is open source and licensed under the MIT license.

If you use this software in your daily development we would appreciate to receive a postcard of your hometown.

Please send it to: Webparking BV, Cypresbaan 31a, 2908 LT Capelle aan den IJssel, The Netherlands

Related Packages

spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

464,910 591
rolice/laravel-db-switch

Simple and light DB switcher for Laravel.

1,863 3
nwidart/db-exporter

Export your database quickly and easily as a Laravel Migration and all the data...

39,133 377