PHPackages                             iiifx-production/lazy-init - 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. iiifx-production/lazy-init

AbandonedArchivedExtension

iiifx-production/lazy-init
==========================

LazyInit - lazy initialization helper

v1.0.3(9y ago)27.7k↓50%1MITPHPPHP &gt;=5.4

Since Jul 9Pushed 9y ago1 watchersCompare

[ Source](https://github.com/iiifx-production/lazy-init)[ Packagist](https://packagist.org/packages/iiifx-production/lazy-init)[ Docs](https://github.com/iiifx-production/lazy-init)[ RSS](/packages/iiifx-production-lazy-init/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (1)Versions (15)Used By (1)

LazyInit
========

[](#lazyinit)

**LazyInit** - хелпер для быстрого создания методов ленивой(отложенной) инициализации.

[![SensioLabsInsight](https://camo.githubusercontent.com/a7e2b478e5d7a6907eef1ab1b356e809fb774836c979f37270c7233d1845de8b/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f32393331366464662d353533342d343465642d383834392d3038356566666266636265372f6269672e706e67)](https://insight.sensiolabs.com/projects/29316ddf-5534-44ed-8849-085effbfcbe7)

[![Latest Version on Packagist](https://camo.githubusercontent.com/cd406c3376e7e5f5f6ce43d1f2a6c75e07a49e6110db43a9ad78ddfcca1208cb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f69696966782d70726f64756374696f6e2f6c617a792d696e69742e737667)](https://packagist.org/packages/iiifx-production/lazy-init) [![Build Status](https://camo.githubusercontent.com/bd3403d076521ccfc6b78d51bae7789b4a7ee8707fa85c1c901a40805594927b/68747470733a2f2f7472617669732d63692e6f72672f69696966782d70726f64756374696f6e2f6c617a792d696e69742e737667)](https://travis-ci.org/iiifx-production/lazy-init)[![Total Downloads](https://camo.githubusercontent.com/15b45b341d4bfd45104efb8c4794d686cadd8c50046c7f6d4301b1edd1ecf250/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f69696966782d70726f64756374696f6e2f6c617a792d696e69742e737667)](https://packagist.org/packages/iiifx-production/lazy-init)

**Отложенная (ленивая) инициализация** ([Lazy initialization](https://ru.wikipedia.org/wiki/%D0%9E%D1%82%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%BD%D0%B0%D1%8F_%D0%B8%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F)) - приём в программировании, когда некоторая ресурсоёмкая операция (создание объекта, вычисление значения) выполняется непосредственно перед тем, как будет использован её результат. Таким образом, инициализация выполняется «по требованию», а не заблаговременно.

Классический пример использования:

```
class DeepThought
{
    protected $answer;

    public function getAnswer ()
    {
        if ( $this->answer === null ) {
            $this->answer = 42;
        }

        return $this->answer;
    }
}

$deepThought = new DeepThought();
echo $deepThought->getAnswer(); # 42
```

Аналогичный пример с использованием LazyInit:

```
class DeepThought
{
    use \iiifx\LazyInit\LazyInitTrait;

    public function getAnswer ()
    {
        return $this->lazyInit( function () {
            return 42;
        } );
    }
}

$deepThought = new DeepThought();
echo $deepThought->getAnswer(); # 42
```

Установка
---------

[](#установка)

Используя Composer:

```
$ composer require "iiifx-production/lazy-init:1.*"
```

Использование
-------------

[](#использование)

LazyInitTrait содержит метод lazyInit() и свойство $lazyInitData, в котором буферизирует результаты вычислений. Предназначен для использования в объектах в динамическом контексте.

```
mixed lazyInit( Closure $container, string|array $dependency = null, array $params = [] )
```

- **$container** - Closure-контейнер, содержащий в себе вычисления, должен вернуть результат.
- **$dependency** - Строка, массив зависимостей или null - для сохранения результата вычисления. Если не указывать ключ, то он будет сгенерирован автоматически.
- **$params** - Дополнительные данные, которые будут переданы в Closure-контейнер при его запуске.

LazyInitStaticTrait содержит метод lazyInitStatic() и свойство $lazyInitStaticData, в котором буферизирует результаты вычислений. Предназначен для использования в статических классах в статическом контексте.

```
mixed lazyInitStatic( Closure $container, string|array $dependency = null, array $params = [] )
```

Параметры метода аналогичны.

Методы способны автоматически генерировать ключ для буферизации данных основываясь на точке вызова в коде. Это реализуется с использованием функции [debug\_backtrace()](http://www.php.net/manual/ru/function.debug-backtrace.php).

Примеры
-------

[](#примеры)

Простой геттер:

```
class Lazy
{
    use \iiifx\LazyInit\LazyInitTrait;

    /**
     * @return string
     */
    public function getDate ()
    {
        return $this->lazyInit( function () {
            return date( 'd.m.Y' );
        }, __METHOD__ );
    }
}

$lazy = new Lazy();
echo $lazy->getDate(); # '12.07.2015'
```

Простой геттер с автоматическим созданием ключа:

```
class Lazy
{
    use \iiifx\LazyInit\LazyInitTrait;

    /**
     * @return string
     */
    public function getMicrotime ()
    {
        return $this->lazyInit( function () {
            return microtime( true );
        } );
    }
}

$lazy = new Lazy();
echo $lazy->getMicrotime(); # 1438928722.9734
```

Геттеры с зависимостью от входящих значений:

```
class Lazy
{
    use \iiifx\LazyInit\LazyInitTrait;

    /**
     * @param string $string
     *
     * @return mixed[]
     */
    public function parseString ( $string )
    {
        return $this->lazyInit( function () use ( $string ) { # Передаем параметр в замыкание напрямую
            return explode( ':', $string );
        }, [
            __METHOD__,
            $string,
        ] );
    }

    /**
     * @param int $timastamp
     *
     * @return string
     */
    public function formatTimastamp( $timastamp )
    {
        return $this->lazyInit( function ( $t ) {
            return date( 'd.m.Y', $t );
        }, [
            __METHOD__,
            $timastamp,
        ], [
            $timastamp # Передаем параметр как свойство
        ] );
    }
}

$lazy = new Lazy();
var_export( $lazy->parseString( 'A:B:C' ) ); # [ 0 => 'A', 1 => 'B', 2 => 'C' ]
var_export( $lazy->formatTimastamp( time() ) ); # '12.07.2015'
```

Использование в статических методах:

```
class LazyStatic
{
    use \iiifx\LazyInit\LazyInitStaticTrait;

    /**
     * @return string
     */
    public static function getDate ()
    {
        return self::lazyInitStatic( function () {
            return date( 'd.m.Y' );
        }, __METHOD__ );
    }
}

echo LazyStatic::getDate(); # '12.07.2015'
```

Использование хелпера за пределами классов:

```
use iiifx\LazyInit\LazyInitHelper;

function buildString( $array )
{
    return LazyInitHelper::lazyInit( function ($v) {
        return implode( '.', $v );
    }, 'build-string', [ $array ] );
}

echo buildString( [ 1, 5, 32 ] ); # '1.5.32'
```

Использование при создании одиночки([Singleton](https://ru.wikipedia.org/wiki/%D0%9E%D0%B4%D0%B8%D0%BD%D0%BE%D1%87%D0%BA%D0%B0_(%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD_%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F))):

```
class Singleton
{
    use \iiifx\LazyInit\LazyInitStaticTrait;

    private function __construct () {}
    private function __clone () {}
    private function __wakeup () {}

    /**
     * @return static
     */
    public static function getInstance ()
    {
        return static::lazyInitStatic( function () {
            return new static();
        }, __METHOD__ );
    }
}
$instance = Singleton::getInstance();
```

Использование при создании пула одиночек([Multiton](https://en.wikipedia.org/wiki/Multiton_pattern)):

```
class Multiton
{
    use \iiifx\LazyInit\LazyInitStaticTrait;

    private function __clone () {}
    private function __wakeup () {}

    public $key;

    protected function __construct ( $key )
    {
        $this->key = $key;
    }

    /**
     * @param string $key
     *
     * @return static
     */
    public static function getInstance ( $key )
    {
        return static::lazyInitStatic( function ( $key ) {
            return new static( $key );
        }, $key, [ $key ] );
    }
}

echo Multiton::getInstance( 'master' )->key; # 'master'
echo Multiton::getInstance( 'slave' )->key; # 'slave'
echo Multiton::getInstance( 'master' )->key; # 'master'
```

Тесты
-----

[](#тесты)

[![Build Status](https://camo.githubusercontent.com/bd3403d076521ccfc6b78d51bae7789b4a7ee8707fa85c1c901a40805594927b/68747470733a2f2f7472617669732d63692e6f72672f69696966782d70726f64756374696f6e2f6c617a792d696e69742e737667)](https://travis-ci.org/iiifx-production/lazy-init) [![Code Coverage](https://camo.githubusercontent.com/912b793837ce5b0228499e01b6cb1a7af2ac7d889998a781fd3329a42f86c86b/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f69696966782d70726f64756374696f6e2f6c617a792d696e69742f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/iiifx-production/lazy-init/?branch=master)

Лицензия
--------

[](#лицензия)

[![Software License](https://camo.githubusercontent.com/074b89bca64d3edc93a1db6c7e3b1636b874540ba91d66367c0e5e354c56d0ea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e737667)](LICENSE.md)

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity26

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 97.4% 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 ~45 days

Recently: every ~98 days

Total

12

Last Release

3464d ago

Major Versions

v0.3.4 → v1.0.02016-05-13

### Community

Maintainers

![](https://www.gravatar.com/avatar/c38df6d1bb48765cd3e07f39c58e0d384e0e3d9a9fd69068ab3149bc2fa1c5fc?d=identicon)[IIIFX](/maintainers/IIIFX)

---

Top Contributors

[![iiifx](https://avatars.githubusercontent.com/u/3157964?v=4)](https://github.com/iiifx "iiifx (38 commits)")[![bitdeli-chef](https://avatars.githubusercontent.com/u/3092978?v=4)](https://github.com/bitdeli-chef "bitdeli-chef (1 commits)")

---

Tags

helperiiifxtraityii2phplazylazy-init

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/iiifx-production-lazy-init/health.svg)

```
[![Health](https://phpackages.com/badges/iiifx-production-lazy-init/health.svg)](https://phpackages.com/packages/iiifx-production-lazy-init)
```

###  Alternatives

[pestphp/pest-plugin-stressless

Stressless plugin for Pest

67792.6k16](/packages/pestphp-pest-plugin-stressless)

PHPackages © 2026

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