PHPackages                             malbrandt/lori - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. malbrandt/lori

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

malbrandt/lori
==============

Laravel steroids intended to help developers. Can speed up developers with helper functions, utility classes, application's performance with its awesome features and many more.

0.25.0(6y ago)023MITPHP

Since Feb 28Pushed 6y ago1 watchersCompare

[ Source](https://github.com/malbrandt/lori)[ Packagist](https://packagist.org/packages/malbrandt/lori)[ Docs](https://github.com/malbrandt/lori)[ RSS](/packages/malbrandt-lori/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (6)Versions (7)Used By (0)

Lori
====

[](#lori)

 [![Malbrandt/Lori Logo](resources/ml-01-logo-thumb.png)](resources/ml-01-logo-thumb.png)

[![Latest Version on Packagist](https://camo.githubusercontent.com/ff41fdd19067e01553eec6810143823be71e4bc0f461931bd8aca3fbbfd7755e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d616c6272616e64742f6c6f72692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/malbrandt/lori)[![Total Downloads](https://camo.githubusercontent.com/6d51226ad300a7dc65717a0270b472d6fffd77f2753af73e96503c0a9f8c6627/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d616c6272616e64742f6c6f72692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/malbrandt/lori)[![Build Status](https://camo.githubusercontent.com/3f5422616f475baf5e317adb85e4dfcd24f97d94a07d804c242150a80dc1032d/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6d616c6272616e64742f6c6f72692f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/malbrandt/lori)[![StyleCI](https://camo.githubusercontent.com/afc25ebded09a6765c171dd3c2ac6b64bf535c31fdb457030953c48c549864b1/68747470733a2f2f7374796c6563692e696f2f7265706f732f3137333136343833352f736869656c64)](https://styleci.io/repos/173164835)

Library that was created in order to help Laravel's developers in their work. It's consist of a suite of usefull functions and conceptions, that can help you speed up prototyping process, optimize application performance, add more readability to your codebase etc. It supplements Laravel with missing functions, that make it an even better and convenient framework.

Code examples
-------------

[](#code-examples)

Below you can find global helper functions reference with short description and usage examples.

  Function Description Examples   access\_prop Reads or assign value for non accessible class property (private/protected). ```
// Read value of the non accessible property (private or protected).
$object = new class() { private $foo = 'bar'; };
$value = access_prop($object, 'foo'); // $value = 'bar'
// Set value to the non accessible property.
$object = new class() { protected $foo = 'bar'; };
access_prop($object, 'foo', 'biz'); // $object->foo = 'biz'
access_prop($object, 'foo', null, true); // $object->foo = null
```

call\_methodCalls class method - even if it's not accessible (private/protected).```
// Instance methods
$obj = new class() { private function foo() { return 'foo'; } };
$result = call_method('foo', $obj); // 'foo'
// Static methods
$obj = new class() { protected static function bar($args) { return $args; } };
$result = call_method('bar', $obj, [1, 2, 3]); // [1, 2, 3]
```

callerReturns info (array) with caller info from debug\_stacktrace method. Can be useful for tracing.```
$caller = caller(); // ['file' => ..., 'line' => ..., 'class' => ..., ...] (full info from debug_stacktrace)
$caller = caller(1, 'function') // i.e. 'eval', name of function, where caller() function was called
$caller = caller(2, 'class') // specified part of caller (class), i.e. 'UserController'
$caller = caller(1, ['function', 'class']); // specified parts of caller (array), i.e. ['function' => ..., 'class' => ...]
```

carbonizeUnifies various date formats into \\Illuminate\\Support\\Carbon object instance.```
// Valid conversions:
$carbon = carbonize('2015-02-05');
$carbon = carbonize('2018-06-15 12:34:00');
$carbon = carbonize('first day of May 2000');
$carbon = carbonize(new \DateTime());
$carbon = carbonize(new \DateTimeImmutable());
// If conversion fails, null will be returned.
$carbon = carbonize('foobar'); // null
```

clampClamps value in given range.```
$clamped = clamp(10);           // 10.0
$clamped = clamp(10, 5);        // 5.0
$clamped = clamp(10, 5, 15);    // 5.0
$clamped = clamp(20, 5, 15);    // 15.0
```

classifyReturns type of the variable (value types) or a class name (reference types).```
classify('1');              // 'integer'
classify('1.23');           // 'double' (or 'float', or 'real' - depends on platform)
classify([]);               // 'array'
classify(new \App\User);    // 'App/User' (instance passed)
classify(\App\User::class); // 'App/User' (string with FQCN passed)
classify('test');           // 'string'
```

cliReturns console helper instance. Could be used for tracing.```
cli()->getOutput()->writeln('foo');
cli()->getInput()->getArguments();
```

cli\_inThe shortcut for `cli()->getInput()`.```
cli_in()->getArguments();
```

cli\_outThe shortcut for `cli()->getOutput()`.```
cli_out()->writeln('bar');
```

console\_logGenerates HTML with &lt;script&gt; that will console.log passed $data.```
$data = [1, 2, 3];
$html = console_log($data); // assigns output to $html
console_log($data, true); // prints output: 'console.log([1,2,3]);'
```

create\_fakeThe shortcut for factory($class)-&gt;create()```
// Pass model's class name:
create_fake(\App\User::class);
// Pass model's instance:
create_fake(User::inRandomOrder()->first());
// Specify number of fakes:
create_fake(\App\User::class, 3);
// Specify overrides:
create_fake(\App\User::class, 1, ['email' => 'marek.malbrandt@gmail.com']);
```

equalsSafely compares two float numbers.```
0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 == 1.0 // false
equals(0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1, 1.0); // true
equals(1.0, 1.0); // true
equals(2.0, 1.0); // false
```

filelineReturns file and line number, from which the functions was called.```
class UserController extends Controller
{
    public static function foo() { return fileline(); }
}
UserController::foo(); // UserController.php:3
```

flash\_errorAn alias for `session()->flash('error', $msg)`.```
flash_error('Message'); // flash error under "error" key
flash_error('Message', ['Error1', 'Error2']); // flash message and errors (under "errors" key)
flash_error('Message', null, 'user.error'); // flash message under "user.errors" key
flash_error(null, ['Error3', 'Error4'], null, 'validation.errors'); // flash message under "validation.errors" key
```

flash\_infoAn alias for `session()->flash('info', $msg)`.```
flash_info('Foobar'); // flashes message under "info" key
flash_info('Foobar', 'lori.info'); // flashes message under custom key: "lori.info"
```

flash\_successAn alias for `session()->flash('success', $msg)`.```
flash_success('Foobar'); // flashes message under "success" key
flash_success('Foobar', 'lori.success'); // flashes message under custom key: "lori.success"
```

flash\_warningAn alias for `session()->flash('warning', $msg)`.```
flash_warning('Foobar'); // flashes message under "warning" key
flash_warning('Foobar', 'lori.warning'); // flashes message under custom key: "lori.warning"
```

has\_traitExamines if a class/object has given trait.```
// Namespace omitted for readability
$obj = new class() { use ValidatesRequests; };
has_trait(ValidatesRequests::class, $obj); // true
has_trait(FooTrait::class, $obj); // false
// Using class name (we're assuming, that Controller class uses ValidatesRequest trait)
has_trait(ValidatesRequests::class, Controller::class); // true
```

make\_fakeThe shortcut for factory($class)-&gt;make()```
// Pass model's class name:
make_fake(\App\User::class);
// Pass model's instance:
make_fake(User::inRandomOrder()->first());
// Specify number of fakes:
make_fake(\App\User::class, 3);
// Specify overrides:
make_fake(\App\User::class, 1, ['email' => 'marek.malbrandt@gmail.com']);
```

methodReturns caller in various useful formats.```
method(); // caller as valid PHP callable (does not support Closures)
method(3); // caller of caller (as a callable)
method(2, METHOD_FORMAT_ACTION); // returns caller in format: FooClass@barMethod
method(2, METHOD_FORMAT_ACTION_FQCN); // returns caller in format: Class\Namespace\Foo@biz
```

onRegister event listeners. Shortcut for Event::listen($events, $callback).```
on(CommandStarting::class, function ($event) {
    $event->output->writeln("Executing command: {$event->command}.");
});
```

random\_floatGenerates a cryptographically secure random float from given range.```
random_float(); // random float in range: 0 < x  UserServiceImpl::class]);
// Pass Closure that resolves singleton instance
$resolver = function () { return new UserServiceImpl(); };
register_singletons([UserService::class => $resolver]);
// Pass object instance that should be a singleton:
$manager = new class () implements UserService {
    private function foo() { return 'bar'; }
};
register_singletons([UserService::class => $manager]);
```

sometimesReturns drawn value with specified probability. Can be useful for generating fake data.```
sometimes('foo'); // returns 'foo' with 10% chance (null otherwise)
sometimes('bar', 0.3); // returns 'bar' with 30% chance (null otherwise)
sometimes('biz', 0.7, 'buzz'); // returns 'biz' with 70% chance ('buzz' otherwise)
```

str\_betweenReturns part of a string between two string.```
str_between('Foo Bar Bizz Buzz');                           // 'Foo Bar Bizz Buzz'
str_between('Foo Bar Bizz Buzz', 'Bar ', ' Buzz');          // 'Bizz'
str_between('Foo Bar Bizz Buzz', 'Foo ', ' Buzz', true);    // 'Bar Bizz Buzz'
// Cuts from the beginning when cannot find cut's left bound
str_between('Foo Bar Bizz Buzz', 'ZZZ ', ' Buzz');          // 'Foo Bar Bizz '
str_between('Foo Bar Bizz Buzz', null, ' Buzz');            // 'Foo Bar Bizz '
// Cuts to the end when cannot find cut's right bound
str_between('Foo Bar Bizz Buzz', 'Foo ', 'Bizzz');          // 'Bar Bizz Buzz'
str_between('Foo Bar Bizz Buzz', 'Foo ', null);             // 'Bar Bizz Buzz'
// Returns an empty string when left bound is equal to right bound
str_between('Foo Bar Bizz Buzz', 'Bizz ', 'Bizz ');         // ''
wstr_between(''); // ''
str_between(null); // null
```

to\_stringConverts passed value to its closest string representation. Useful for tracing.```
to_string($str = 'foobar'); // 'foobar'
to_string($int = 123);      // '123'
to_string($float = 123.45); // '123.45'
to_string($null = null);    // 'null'
to_string($array = [1, 2]); // '[1,2]' (JSON)
to_string($bool = true);    // 'true'
to_string($object);         // json_encode($object)
// Assuming that $xml is a SimpleXmlElement
to_string($xml);            // $xml->asXML()
```

str\_cropCuts off end of the string if it is too long. Can be used for data sanitization.```
str_crop('FooBarBizz', 3);              // 'Foo'
str_crop('FooBarBizz', 6);              // 'FooBar'
str_crop('', 10);                       // ''
str_crop(null, 123);                    // ''
// Specify custom encoding (by default it is 'UTF-8')
str_crop('FooBarBizz, 3, 'ISO-8859-1'); // 'FooBarBizz'
```

str\_removeRemoves given fragments from the original string.```
str_remove('Foo Bar Biz');                  // 'Foo Bar Biz'
str_remove('Foo Bar Biz', 'Foo');           // ' Bar Biz'
str_remove('Foo Bar Biz', 'Foo', 'Bar');    // '  Biz'
str_remove('Foo Bar Biz', 'Bar', 'Biz');    // 'Foo  '
str_remove('Foo Bar Biz', 'Buzz');          // 'Foo Bar Biz'
```

model\_tableReturns the name of model's table.```
model_table(\App\User::class); // 'users' (passed class name)
model_table(new \App\User());  // 'users' (passed model's instance)
model_table('FooBar');         // throws InvalidArgumentException when cannot examine
```

@TODO - place some examples here.

Documentation
-------------

[](#documentation)

List of functions can be founf here (@TODO create that list). Except that, the code is well documented and contains a lot code examples. If you had any questions regarding the code, feel free to ask. The best way to do this is to find or create new topic on forum (issue with label "question" or "help needed").

Requirements
------------

[](#requirements)

- Laravel
- PHP

@TODO - examine exact versions

Installation
------------

[](#installation)

Library can be downloaded and installed automatically using Composer.

```
composer require malbrandt/lori

```

Tests
-----

[](#tests)

### Running the tests

[](#running-the-tests)

In order to run tests, type into console:

```
$ composer test
```

### Global functions

[](#global-functions)

Each global function has got suite of unit tests in separate file. That files are placed in directory `app/tests/Helpers`. In example, if a function is named `access`, test class `AccessTest` will be placed in file `app/tests/Helpers/AccessTest.php`.

### Classes

[](#classes)

Bigger conceptions that require separate class to be implemented also have got test suites. Test files are placed in directory `tests`. Their localisation corresponds to namespaces of classes, according to PSR-4 convention. In example `Malbrandt/Lori/Database/Autofactory` class will have its tests in class `AutofactoryTest` in file `src/Database/AutofactoryTest.php`.

### Writing tests

[](#writing-tests)

For unit tests we are using PHPUnit library and Orchestra framework (@TODO provide urls). All methods has `@test` directive in theirs PHPDocBlock. Test method names are formuled in behavioral form, it means that they describes some feature or capabilities of some object, class or function. Examples:

```
/** @test */
public function retores_previous_access_modifier_after_reading_property_value() { /** … */ }

/** @test */
public function retores_previous_access_modifier_after_modifying_property_value() { /** … */ }
```

Code style
----------

[](#code-style)

Coding conventions are the same as in Laravel framework. The code should be written in such a way that the whole library has the minimum requirements. If you need to use function from newer Laravel version, place this information on special list: ... (@TODO: create list). Certainly your attention will be taken into account during the development of newer library's MAJOR version. Only then will we be able to use the newer version of Laravela or PHP (due to backward compatibility).

@TODO - describe StyleCI

Contributing
------------

[](#contributing)

If you want to add your 5 cents to this library, you can do this in many ways. Here are few of them:

- propose change: a new function, change of some function (paremetrize its algorithm settings?), supplementing the documentation (where?), adding an example (for which function?), etc.
- if something is incomprehensible or too poorly explained - inform about it as fast as possible!
- take part in a discussion in existing Issue Tracker topics,
- propose interesting concept (concepts examples: batch insert, DTO, autofactories, dynamic parameters),
- deal with the function from the to-do list,
- fill in the gaps in the documentation,
- add some unusual test or test scenario,
- add code example with some function usage,
- make code review of someone changes (Pull Requests),
- write an article about some feature from this library with some great explanation of concepts and code examples (once written, link it in readme file in section `Further reading`),
- do the things TODO :)

Versioning
----------

[](#versioning)

This library uses [Semantic Versioning 2.0.0](https://semver.org/). We can assume that each subsequent minor version must consist of at least one new function. Any corrections (obviously compatible backwards) in the code or documentation will be included in the "patch" part of the version.

Credits
-------

[](#credits)

- Marek Malbrandt - author.

License
-------

[](#license)

Copyright (c) Marek Malbrandt

The Laravel framework is open-source software licensed under the [MIT license](https://opensource.org/licenses/MIT).

@TODO - choose and describe Open Source license.

Acknowledgements
----------------

[](#acknowledgements)

For the creators of the Laravel framework and all libraries that were used to create this library and the libraries that these libraries use...

ToDo's
------

[](#todos)

### Concepts

[](#concepts)

- ArrayToExcel
- Autofactory
- Autoforms
- Automemoization
- AutoValidation
- BatchInsert
- CLI
- CreateOrIncrement
- CreatesReferences
- Deferred (execution)
- DisplayProgress
- DTO
- DynamicParameters
- Enum
- GatherQueries
- HasValidationRules
- Identifiable
- Measure
- MeasureResponseTimes
- Memoizaiton
- NotImplementedException
- RegisterRoutes
- RelativeDate
- RequestFilters
- RouteLocks
- SelectiveFind
- SelectOptions
- Service
- Str
- TranslatableEnum
- Url
- ValidationHelpers

### Helper functions

[](#helper-functions)

- access\_prop
- batch\_insert
- call\_method
- caller
- carbonize
- Collection::duplicates
- Collection::duplicatedBy
- clamp
- classify
- cli
- cli\_in
- cli\_out
- console\_log
- create\_fake
- equals
- fileline
- flash\_error
- flash\_info
- flash\_success
- flash\_warning
- has\_trait
- make\_fake
- method
- on
- random\_float
- register\_singletons
- sometimes
- str\_between
- to\_string
- str\_crop
- str\_remove
- model\_table
- trace

###  Health Score

24

—

LowBetter than 31% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~42 days

Total

5

Last Release

2509d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/778ad27b3a10b94fdfcdbc6c3a32890eca5dab6001d5162ed6cea2ae40bd2d04?d=identicon)[Malbrandt](/maintainers/Malbrandt)

---

Top Contributors

[![malbrandt](https://avatars.githubusercontent.com/u/1521332?v=4)](https://github.com/malbrandt "malbrandt (35 commits)")

---

Tags

classesfunctionshelperslaravellibrarymemoizationmiddlewaretraitslaravellori

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/malbrandt-lori/health.svg)

```
[![Health](https://phpackages.com/badges/malbrandt-lori/health.svg)](https://phpackages.com/packages/malbrandt-lori)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[renatomarinho/laravel-page-speed

Laravel Page Speed

2.5k1.7M11](/packages/renatomarinho-laravel-page-speed)[vinkius-labs/laravel-page-speed

Laravel Page Speed

2.5k9.6k1](/packages/vinkius-labs-laravel-page-speed)[emargareten/inertia-modal

Inertia Modal is a Laravel package that lets you implement backend-driven modal dialogs for Inertia apps.

90128.1k](/packages/emargareten-inertia-modal)[linkxtr/laravel-qrcode

A clean, modern, and easy-to-use QR code generator for Laravel

3614.9k](/packages/linkxtr-laravel-qrcode)[wearepixel/laravel-cart

A cart implementation for Laravel

1355.6k](/packages/wearepixel-laravel-cart)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
