mattjmattj/maybe

伪造对象以实现更简洁的代码和错误处理

1.0.2 2015-03-20 21:24 UTC

This package is auto-updated.

Last update: 2024-09-12 03:50:53 UTC


README

Build Status Scrutinizer Code Quality Code Coverage

Maybe 可以包装一个类,并提供一种处理未定义实例时抽象错误处理的方法。它可能有助于实现功能开关、开发/生产环境切换等。

安装

使用 composer

composer.phar require mattjmattj/maybe ~1.0

基本用法

use Maybe\Maybe;

/*
 * Create a Maybe instance for the desired class or interface.
 */
$maybe = new Maybe('Some\Class');

/*
 * Wrap some object that you don't know much about : 
 * might be null or an actual instance of Some\Class.
 */
$wrapped = $maybe->wrap($someContainer->getSomeClassInstance());

/*
 * Call whatever you want on the wrapped object without having
 * to worry about whether $someContainer->getSomeClassInstance()
 * return something or not.
 */
$wrapped->doSomeInterestingThing();

/*
 * You can also call a method at a deeper level. Maybe will wrap returned types
 * if it finds proper @return annotations
 */
$wrapped->getSomeService()->doSomeJob();

示例

示例在 "example" 文件夹中提供

  • 日志 : 使用 Maybe 与 IoC 容器包装 "日志" 功能并编写无忧代码的示例。
  • 电子邮件 : 使用 Maybe 仅从接口创建伪造对象的示例。深层包装的示例。

警告

并非每种类型的对象都应该被包装。通常,您会希望包装提供日志、调试、缓存、事件等功能的类。您不希望包装实际改变代码逻辑的“有用”类。

许可

Maybe 在 BSD-2-Clause 许可下授权。