You are here

6 在保存面包屑时,更新对应的静态缓存

admin 的头像
Submitted by admin on 星期五, 2015-09-18 05:59

作者:老葛,北京亚艾元软件有限责任公司,http://www.yaiyuan.com

前面,我们讲了如何使用drupal_static,新的问题出来了,如果在一个HTTP内,如果我们更新的对应的面包屑对象,更新了之后,再去调用breadcrumb2_load_by_path函数,有可能返回的还是最初的面包屑对象。所以我们有必要在保存面包屑对象的时候,也修改一下这个静态缓存。

class Breadcrumb extends Entity {

….

  public function save() {

    if (empty($this->bid) && (!empty($this->path))) {

      $existing_breadcrumb = breadcrumb2_load_by_path($this->path);

      if(!empty($existing_breadcrumb)){

         $this->bid = $existing_breadcrumb->bid;

         $this->is_new = FALSE;

      }

    }

    parent::save();

    // Update the static cache from breadcrumb2_load_by_path().

    $cache = &drupal_static('breadcrumb2_load_by_path', array());

    if (isset($cache[$this->path])) {

      $cache[$this->path] = $this;

    }

  }

}

这是对面包屑对象保存,改进后的代码,就是我们在保存一个面包屑对象后,对对应的静态缓存也做了更新。

有兴趣的读者,可以在breadcrumb2_load_by_path里面加上几句drupal_set_message这样的调试代码,观察一下,同一个HTTP请求内,IF语句里面的代码被调用了多少次。


Drupal版本: