Zend_Registryの使い方。

By katou - 08/10/17 - このエントリをはてなブックマークに追加このエントリをYahoo!ブックマークに追加このエントリをdel.icio.usに追加このエントリをFC2ブックマークに追加

Zend_Registryの機能はアプリケーション内で、特定の値を保持するためのコンテナです。

Zend_Registryの特徴は、関係が無いクラス同士でも、特定の値を共有出来きるグローバル変数のようなものです。

用途としては、PCサイト・携帯サイト作成に関わらず、ひとつのサイトで特定の値を何度も使うので、使い回したい時や、

変数の値を一元管理したい。等、使用頻度の高い値をアプリケーション内で使う場合、大変便利です。

今回は、IndexController.phpでZend_Registryに値を登録し、登録したコントローラーとは継承関係の無い

SampleController.phpでZend_Registryに登録されている値を出力します。

IndexController.php

<?php

require_once 'Zend/Controller/Action.php';

class Member_IndexController extends Zend_Controller_Action
{
  public function indexAction()
  {
    //「インデックス名,値」と登録しています
    Zend_Registry::set('index',"Registry::setでセットした値");
    //SampleControllerのindexアクションを指定しています
    $this->_forward('index','Sample');
    //インスタンスを取得しています
    $registry = Zend_Registry::getInstance();
    //hogeをインデックスとし、配列を登録してます
    $registry->set('hoge',array('配列を格納','hoge','hoge'));
  }

}

SampleController.php

<?php

require_once 'Zend/Controller/Action.php';

class Member_SampleController extends Zend_Controller_Action
{
    public function indexAction()
    {
      //インデックス名に紐づく値を変数に代入してます
      $string  = Zend_Registry::get('index');
      $array  = Zend_Registry::get('hoge');
      echo$string."<br />";
      var_dump($array);
    }

}

Zend_Registryのマニュアルです。