settleup/can-make-or-fake

A simple helper for making classes easily instantiated and mocked.

Maintainers

Package info

github.com/trysettleup/can-make-or-fake

Homepage

pkg:composer/settleup/can-make-or-fake

Fund package maintenance!

trysettleup

Statistics

Installs: 25

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.1 2026-04-11 00:09 UTC

This package is auto-updated.

Last update: 2026-04-11 00:11:07 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

A lightweight Laravel trait that gives any class a make() static constructor (resolved through the container) and a fake() method for easy test mocking.

Installation

composer require settleup/can-make-or-fake

Usage

Add the CanMakeOrFake trait to any class:

use SettleUp\CanMakeOrFake\CanMakeOrFake;

class PriceCalculator
{
    use CanMakeOrFake;

    public function calculate(int $quantity, int $unitPrice): int
    {
        return $quantity * $unitPrice;
    }
}

Resolving instances with make()

make() resolves the class through Laravel's service container, so any constructor dependencies are automatically injected:

$calculator = PriceCalculator::make();

$total = $calculator->calculate(quantity: 3, unitPrice: 500); // 1500

Faking in tests with fake()

fake() creates a Mockery partial mock and binds it into the container. Any subsequent call to make() (or container resolution) will return the mock:

use Mockery\MockInterface;

PriceCalculator::fake(function (MockInterface $mock) {
    $mock->shouldReceive('calculate')->andReturn(0);
});

// Anywhere in your application that resolves PriceCalculator will now get the fake
$calculator = PriceCalculator::make();
$calculator->calculate(3, 500); // 0

Because fake() creates a partial mock, any methods you don't explicitly mock will still call the real implementation.

Conditionable

The trait includes Laravel's Conditionable trait, so you can use when() and unless():

$calculator = PriceCalculator::make();

$calculator->when($applyDiscount, function (PriceCalculator $calc) {
    // ...
});

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.