xiyusullos / nullable
无论对象是否为null,都可以在对象上连续调用链式方法
0.2.0
2017-03-22 18:59 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ^6.0
This package is not auto-updated.
Last update: 2024-09-25 00:10:45 UTC
README
安装
使用以下命令安装最新版本
composer require xiyusullos/nullable
使用方法
基本使用
<?php use xiyusullos\Nullable; class Obj { use Nullable; // ... } $obj = new Obj(); echo $obj->a->b->c;
Laravel 使用
<?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;
关于
作者
许可协议
Nullable
使用 MIT 许可协议 - 有关详细信息,请参阅 LICENSE
文件