maarky/lazy

懒加载器

1.0.0 2017-10-31 03:30 UTC

This package is auto-updated.

Last update: 2024-08-29 04:41:31 UTC


README

此库提供了一种基本的懒加载方法。如果你厌倦了编写如下代码,那么你可以从这个类中受益。

class Whatever
{
    public $something;
    
    public function getSomething()
    {
        if(!$something) {
            $this->something = 'something';
        }
        return $this->something;
    }
}

这种方法存在一些问题

  • 存在讨厌的样板代码。
  • 实际值 $something 可能评估为 false,这意味着你需要更多的样板代码。
  • 你的类必须知道如何获取 $something。

用法

假设你有一个 Author 对象和一个 getArticles() 方法,该方法返回该作者的所有文章的数组。如果你在代码的 100 个地方使用此对象,但你只需要一半的地方的文章列表,那么你不会希望在每次创建 Author 对象时都加载文章,因为所花费的时间通常会被浪费。

Lazy\Container 类构造函数接受一个不接受任何参数并返回任何值的回调函数。get() 方法调用该函数,存储返回的值并返回它。如果你再次调用 get() 方法,它将不会调用你的函数,而是直接返回之前生成的值。

这是一个示例,其中仓库类创建你的 Author 实例

class AuthorRepository
{
    public function find($id)
    {
        //query db for author with the given id
        //resulting an an array called $row
        
        $function = function() use($id) {
            return $this->articleRepository->findByAuthor($id)
        };
        $row['articles'] = new \maarky\Lazy\Container($function);
        return new Author($row);
    }
}

class Author
{
    public function getArticles()
    {
        return $this->articles->get();
    }
}

如你所见,getArticles() 方法不需要知道有关如何检索文章或它们是否已经检索的任何信息。它只需从 Lazy\Container 对象中获取值,并让该对象处理细节。

警告

重要的是要知道这个值只会生成一次。这意味着它是不可变的。如果应用程序或包含 Lazy.Container 对象的对象中的任何更改需要为该 Lazy.Container 对象生成新的值,那么你不应该使用此类。

这种行为是有意为之的,它是功能之一,而不是错误。