{"id":26324979,"url":"https://github.com/andy87/lazy-load-trait","last_synced_at":"2026-02-27T03:32:51.576Z","repository":{"id":274104640,"uuid":"921926031","full_name":"andy87/lazy-load-trait","owner":"andy87","description":"Yii2 Trait загрузки классов по запросу","archived":false,"fork":false,"pushed_at":"2025-04-06T11:29:26.000Z","size":56,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-16T17:09:55.056Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/andy87.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-01-24T22:06:51.000Z","updated_at":"2025-04-06T11:29:29.000Z","dependencies_parsed_at":null,"dependency_job_id":"77699ed6-7d49-4b77-b81c-112bcde145f6","html_url":"https://github.com/andy87/lazy-load-trait","commit_stats":null,"previous_names":["andy87/yii2-lazy-load-trait","andy87/lazy-load-trait"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/andy87/lazy-load-trait","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy87%2Flazy-load-trait","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy87%2Flazy-load-trait/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy87%2Flazy-load-trait/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy87%2Flazy-load-trait/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andy87","download_url":"https://codeload.github.com/andy87/lazy-load-trait/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andy87%2Flazy-load-trait/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29883750,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-26T23:51:21.483Z","status":"online","status_checked_at":"2026-02-27T02:00:06.759Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-15T18:29:33.948Z","updated_at":"2026-02-27T03:32:51.561Z","avatar_url":"https://github.com/andy87.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"Вот такая реализация пришла в голову.\n\nИнициализация свойства класса только в момент вызова(обращения к ним).\nP.S. Знаю что в PHP c версии 8.4 появилась поддержка lazyLoad из коробки, но это ещё не завезли в Yii2.\n\nУстановка.\n\nComposer:\n```bash\ncomposer require andy87/lazy-load-trait\n```\n\n## Использование. Порядок дейсвий.\n\n### 1. Аннотации\nУказать свойство в аннотации класса\n```php\n/**\n * SomeClass\n *\n * @property-read SomeComponent $someComponent // native\n * @property-read OtherComponent $_otherComponent // singleton\n * \n * @package yii2\\controllers\n */\nclass SomeClass\n{\n    //...\n}\n```\n\n### 2. Добавление use\nДля подключения трейта в классе имеется 2 варианта Trait'ов:\n* `andy87\\lazy_load\\yii2\\LazyLoadTrait` - для использования в фреймворке Yii2 с применением метода `Yii::createObject()`\n* `andy87\\lazy_load\\LazyLoadTrait` - для использования вне фреймворка Yii2\n\n### 3. Конфигурация свойств\nуказать конфигурацию в свойстве `$lazyLoadConfig`\n\nСтруктура конфигурации.\n* для использования свойства как экземпляр класса (без настроек), доступно 2 варианта:\n```php\n    public array $lazyLoadConfig = [\n        'someComponent' =\u003e SomeComponent::class, // быстрый способ ( меньше проверок )\n        'otherComponent' =\u003e [\n            'class' =\u003e OtherComponent::class,  // способ поедленней ( больше проверок )\n        ],\n    ]\n```\n\n* с назначением публичных свойств класса\n```php\n    public array $lazyLoadConfig = [\n      'otherComponent' =\u003e [\n            'class' =\u003e OtherComponent::class,\n            'public_property_1' =\u003e 'value_1',\n            'public_property_2' =\u003e 'value_2',\n        ],\n    ]\n```\n\n* с передачей параметров в аргументы функции `__construct()` \n```php\n    public array $lazyLoadConfig = [\n       'thirdComponent' =\u003e [\n            'class' =\u003e [ ThirdComponent::class, ['construct_argument_1', 'construct_argument_2'] ],\n        ],\n    ]\n```\n* комбинирование назначения публичных свойств и передача параметров в аргументы функции `__construct()`\n```php\n    public array $lazyLoadConfig = [\n         'nextComponent' =\u003e [\n            'class' =\u003e [ NextComponent::class, ['construct_argument_1', 'construct_argument_2'] ],\n            'public_property_1' =\u003e 'value_1',\n            'public_property_2' =\u003e 'value_2',\n        ],\n    ]\n```\n* добавление объекта в `cache` с последующим переиспользованием закешированой версии\n__добавление к имени своства префикса(нижнее подчеркивание `_`)__\n```php\n    public array $lazyLoadConfig = [\n        '_nextComponent' =\u003e [ // данное своство при первом обращении будет закешировано, и при последующих обращениях будет использоваться закешированная версия\n            'class' =\u003e [ NextComponent::class, ['construct_argument_1', 'construct_argument_2'] ],\n            'public_property_1' =\u003e 'value_1',\n            'public_property_2' =\u003e 'value_2',\n        ],\n    ]\n```\n\n\n### 4.Использование\nОбращаться к свойствам как к обычным свойствам класса\n```php\n\u003c?php\n\nnamespace some\\path;\n\nuse andy87\\lazy_load\\LazyLoadTrait;\n\n/**\n * SomeClass\n *\n * @property-read SomeComponent $someComponent\n * @property-read OtherComponent $otherComponent\n * @property-read ThirdComponent $thirdComponent\n * \n * @package yii2\\controllers\n */\nclass SomeClass\n{\n    use LazyLoadTrait;\n\n\n    /** @var array  */\n    public array $lazyLoadConfig = [\n        'someComponent' =\u003e SomeComponent::class,\n        'otherComponent' =\u003e [\n            'class' =\u003e OtherComponent::class,\n            'public_property' =\u003e 'some value'\n        ],\n        '_thirdComponent' =\u003e [\n            'class' =\u003e [ ThirdComponent::class, ['construct_argument_1', 'construct_argument_2'] ],\n        ],\n        '_nextComponent' =\u003e [\n            'class' =\u003e [ NextComponent::class, ['construct_argument_1', 'construct_argument_2'] ],\n            'public_property' =\u003e 'some value'\n        ],\n    ];\n\n    /**\n     * @return string\n     */\n    public function actionView(): string\n    {\n        // Apply LazyLoad\n        $text = $this-\u003esomeComponent-\u003einsideSomeComponent-\u003etest();\n\n        if (Yii::$app-\u003erequest-\u003eisPost) {\n            return $this-\u003eotherComponent-\u003esomeMethod();\n        }\n        \n        if (Yii::$app-\u003erequest-\u003eisAjax) {\n            $text = $this-\u003e_thirdComponent-\u003emextMethod();\n        }\n        \n        if (Yii::$app-\u003erequest-\u003eisDelete) {\n            $text = $this-\u003e_nextComponent-\u003emextMethod();\n        }\n\n        return $this-\u003erender('view', ['text' =\u003e $text]);\n    }\n}\n```\n\n### Для динамической настройки, с получением своств из метода, надо перезаписать метод `findLazyLoadConfig()`\n```php\n\u003c?php\n\nnamespace some\\path;\n\nuse andy87\\lazy_load\\LazyLoadTrait;\n\n/**\n * SomeClass\n *\n * @property-read SomeComponent $someComponent\n * @property-read DymanicConfigComponent $dynamicConfigCmponent\n * \n * @package yii2\\controllers\n */\nclass SomeClass\n{\n    use LazyLoadTrait;\n\n\n    /** @var array  */\n    public array $lazyLoadConfig = [\n        'someComponent' =\u003e [\n            'class' =\u003e SomeComponent::class,\n            'public_property' =\u003e 'some value'\n        ],\n        'dynamicConfigCmponent' =\u003e DymanicConfigComponent::class,\n    ];\n\n    /**\n     * @return string\n     */\n    public function actionView(): string\n    {\n        $message = $this-\u003eotherComponent-\u003einsideSomeComponent-\u003etest();\n        return $this-\u003edynamicConfigCmponent-\u003einsideSomeComponent-\u003etest();\n    }\n    \n    protected function findLazyLoadConfig(string $name): ?object\n    {\n        return match ($name)\n        {\n            'dynamicConfigCmponent' =\u003e [\n                'class' =\u003e [SomeComponent::class, $this-\u003egetArguments() ],\n            ],\n            default =\u003e parent::findCachedObject($name),\n        }\n    }\n}\n```\n\nHome: https://github.com/andy87/lazy-load-trait","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandy87%2Flazy-load-trait","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandy87%2Flazy-load-trait","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandy87%2Flazy-load-trait/lists"}