imanghafoori/laravel-nullable 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

imanghafoori/laravel-nullable

Composer 安装命令:

composer require imanghafoori/laravel-nullable

包简介

A package to help you write expressive defensive code in a functional manner

README 文档

README

Do not let "null" to impersonate your objects.

StyleCI Quality Score Code Coverage Latest Stable Version PHP from Packagist License

Functional programming paradigm in laravel

Built with ❤️ for every smart laravel developer

Null is usually used to represent a missing value (for ex when we can't find a row with a partcular Id we return null) And that is the BAD IDEA, we are going to kill off !!!

🔥 Installation:

composer require imanghafoori/laravel-nullable

This package exposes a nullable() global helper function with which you can wrap variables which sometimes are object and sometimes null.

Consider this:

$email = TwitterApi::find(1)->email;

Now this code is working fine But...

What if the user with ID of 1 gets deleted in future ?!

null->email and crap ! 😧

So if you forget to handle the null with an if statement, you will have errors.

You need something to FORCE you and the users of your class methods to handle the null cases.

To prevent such errors, you should code like this:

$user = $twitterApi->find($id);

if ($user === null) {
    return redirect()->route('page_not_found');
}

▶️ Nullables to rescue !!!

To refactor the code above, first

You have to change your repo class :

// the old way:

/**
* @return User|null            <---- consider here. We are returning two types !!!
*/
public function find ($id) {
     $user = TwitterApi::search($id);
     
     if (!$user) {
         return null;
     }
     return new User($user);   
}

The above code returns 2 types, and That is the source of confusion for method callers. They get ready for one type, and forget about the other.

Let's do a small change to it:

/**
 * @return Nullable        <---- we now have only one consistent type. Not two.
 */
public function find ($id) {
     $user = TwitterApi::search($id);
     
     if (!$user) {
         return new Nullable(null);   //  <----  instead of pure null;
     }
     $user = new User($user);   
     
     $message = 'Model Not Found with Id : '. $id;

     return new Nullable($user, [$message]);   //  <----  instead of User;
}

🔔 Now our method consistently returns Nullable objects, no matter what :)

After this change, no one can have access to the real meat of your repo (in this case User object) unless he/she gives a way to handle the null case. No if(is_null()) is required, No exception handling is required.

Remember PHP does not force us to write that if, and we as humen always tend to forget it.

And that makes a differnce ! Before it was easy to forget, but it is impossible to continue if you forget !!!

$userObj = $userRepo->find($id)->getOrSend(function ($message) {

  return redirect()->route('page_not_found')->with('error', $message);
});

// Call a static method.
$userObj = $twitterApi->find($id)->getOrSend([Response::class, 'pageNotFound']);

// or a get default value
$userObj = $twitterApi->find($id)->getOr(new User());

Now we are sure $user is not null and we can sleep better at night !

▶️ Testing:

An other advantage is that, if you use nullable and you forget to write a test that simulates the situations where null values are returned, phpunit code coverage highlights the closure you have passed to the ->getOrDo() (or similar methods) as none-covered, indicating that there is a missing test.

but if you return the object directly, you can get 100% code coverage without having a test covering nully situations, hence hidden errors may still lurk you at 100% coverage.

▶️ Q & A :

Why throwing exceptions is not always the best idea?!

When you throw an exception you should always ask your self. Is there any body out there to catch it ?? What if they forget to catch and handle the exception ?! It is the same issue as the null. It cases error.

The point is to give no way to continue, if they forget to handle the failures.

More from the author:

Laravel middlewarize (new*)

💎 You can put middleware on any method calls.

Laravel Hey Man

💎 It allows to write expressive code to authorize, validate and authenticate.

Laravel Terminator

💎 A minimal yet powerful package to give you opportunity to refactor your controllers.

Laravel AnyPass

💎 It allows you login with any password in local environment only.

Eloquent Relativity

💎 It allows you to decouple your eloquent models to reach a modular structure

imanghafoori/laravel-nullable 适用场景与选型建议

imanghafoori/laravel-nullable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 472.46k 次下载、GitHub Stars 达 151, 最近一次更新时间为 2019 年 07 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「laravel」 「laravel-package」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 imanghafoori/laravel-nullable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 imanghafoori/laravel-nullable 我们能提供哪些服务?
定制开发 / 二次开发

基于 imanghafoori/laravel-nullable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 472.46k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 151
  • 点击次数: 14
  • 依赖项目数: 7
  • 推荐数: 0

GitHub 信息

  • Stars: 151
  • Watchers: 7
  • Forks: 10
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-07-21