Skip to content

chain calls on object whatever the object is null or not. 一个可以在 Laravel 上,链式 调用 Model 的 relationship 的开源库。免去做 非空 判断 的繁琐步骤。

License

Notifications You must be signed in to change notification settings

xiyusullos/nullable

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Nullable - Chain calls on Null for PHP

Installation

Install the latest version with

composer require xiyusullos/nullable

Usage

Basic Usage

<?php

use xiyusullos\Nullable;

class Obj
{
    use Nullable;
    
    // ...
}

$obj = new Obj();
echo $obj->a->b->c;

Laravel Usage

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use xiyusullos\Nullable;

class Profile extends Model
{
    // supposed an attribute of departmentName
    use Nullable;

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // ...
}

class User extends Model
{
    use Nullable;

    public function profile()
    {
        return $this->hasOne(Profile::class);
    }

    // ...
 }

class Blog extends Model
{
    use Nullable;

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // ...
}

// wanna get the writer's department name who posted the blog #1

// without Nullable
$blog = Blog::find(1);
$user = $blog->user;
if ($user) {
    $profile = $user->profile;
    if ($profile) {
        $departmentName = (string) $profile->departmentName;
    }
} // that's so annoying!

// with Nullable
$blog = Blog::find(1);
$departmentName = (string) $blog->user->profile->departmentName;

About

Author

xiyusullos

License

Nullable is licensed under the MIT License - see the LICENSE file for details

About

chain calls on object whatever the object is null or not. 一个可以在 Laravel 上,链式 调用 Model 的 relationship 的开源库。免去做 非空 判断 的繁琐步骤。

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages