首頁 後端開發 php教程 php Collection种的设计

php Collection种的设计

Jun 13, 2016 pm 01:05 PM
function nbsp public quot this

php Collection类的设计

用。net开发已经很多年了,最近接触到php,发现php也没好玩。不过发现它里面没有集合类,只有数组,并且数组很强。这里我用数组来包装成一个集合Collection,代码如下:

class Collection{
	private $_members=array();
	
	public  function addItem($obj,$key=null)
	{
		if($key)
		{
			if(isset($this->_members[$key]))
			{
				throw  new exception("Key \"$key\" already in use!");
			}
			else
			{
				$this->_members[$key]=$obj;
			}
		}
		else
		{
			$this->_members[]=$obj;
		}
	}
	
	public function removeItem($key)
	{
		if(isset($this->_members[$key]))
		{
			unset($this->_members[$key]);
		}
		else
		{
			throw new exception("Invalid Key \"$key\"!");
		}
	}
	public function getItem($key)
	{
		if(isset($this->_members[$key]))
		{
			return $this->_members[$key];
		}
		else
		{
			throw new  exception("Invalid Key \"$key\"!");
		}
	}
	
	public function Keys()
	{
		return array_keys($this->_members);
	}
	
	public function legth()
	{
		return sizeof($this->_members);
	}
	
	public function exists($key)
	{
		return (isset($this->_members[$key]));
	}
}
登入後複製
现在我们来测试一下这个集合是否好用。

我们首先建立一个集合元素类Course:

class  Course
{
	private $_id;
	private $_courseCode;
	private $_name;
	
  public function __construct($id,$courseCode,$name)
	{
		$this->_id=$id;
		$this->_courseCode=$courseCode;
		$this->_name=$name;
	}
	
	public function getName()
	{
		return $this->_name;
	}
	
	public function getID()
	{
		return $this->_id;
	}
	
	public function getCourseCode()
	{
		return $this->_courseCode;
	}
	
	public function __toString()
	{
		return $this->_name;
	}
}
登入後複製
测试代码如下:

$courses=new Collection();
$courses->addItem(new Course(1, "001", "语文"),1);
$courses->addItem(new Course(2, "002", "数学"),2);
$obj=$courses->getItem(1);
print $obj;
登入後複製
我想这个集合类应该可以满足我们平日开发的需求了吧。
可是我们现在。net里面有个对象延迟加载,举个例子来说吧,假如现在有Student这个对象,它应该有很多Course,但是我们希望在访问Course之前Course是不会加载的。也就是说在实例化Student的时候Course个数为0,当我们需要Course的时候它才真正从数据库读取相应数据。就是需要我们把Collection做成惰性实例化。

修改后的Collection代码如下:

class Collection {

  private $_members = array();    //collection members

  private $_onload;               //holder for callback function

  private $_isLoaded = false;     //flag that indicates whether the callback
                                  //has been invoked

  public function addItem($obj, $key = null) {
    $this->_checkCallback();      //_checkCallback is defined a little later
        
    if($key) {
      if(isset($this->_members[$key])) {
        throw new KeyInUseException("Key \"$key\" already in use!");
      } else {
        $this->_members[$key] = $obj;
      }
    } else {
      $this->_members[] = $obj;
    }
  }

  public function removeItem($key) {
    $this->_checkCallback();
    
    if(isset($this->_members[$key])) {
      unset($this->_members[$key]);
    } else {
      throw new KeyInvalidException("Invalid key \"$key\"!");
    }  
  }
  
  public function getItem($key) {
    $this->_checkCallback();
    
    if(isset($this->_members[$key])) {
      return $this->_members[$key];
    } else {
      throw new KeyInvalidException("Invalid key \"$key\"!");
    }
  }

  public function keys() {
    $this->_checkCallback();
    return array_keys($this->_members);
  }

  public function length() {
    $this->_checkCallback();
    return sizeof($this->_members);
  }

  public function exists($key) {
    $this->_checkCallback();
    return (isset($this->_members[$key]));
  }

  /**
   * Use this method to define a function to be 
   * invoked prior to accessing the collection.  
   * The function should take a collection as a 
   * its sole parameter.
   */
  public function setLoadCallback($functionName, $objOrClass = null) {
    if($objOrClass) {
      $callback = array($objOrClass, $functionName);
    } else {
      $callback = $functionName;
    }
    
    //make sure the function/method is valid
    if(!is_callable($callback, false, $callableName)) {
      throw new Exception("$callableName is not callable " . 
                          "as a parameter to onload");
      return false;
    }
    
    $this->_onload = $callback;
  }
  
  /**
   * Check to see if a callback has been defined and if so,
   * whether or not it has already been called.  If not,
   * invoke the callback function.
   */
  private function _checkCallback() {
    if(isset($this->_onload) && !$this->_isLoaded) {
      $this->_isLoaded = true;
      call_user_func($this->_onload, $this);
    }
  }
}
登入後複製
所需的Student如下:

class CourseCollection extends Collection {
 public function addItem(Course $obj,$key=null) {
		parent::addItem($obj,$key);
	}
}
class Student{
	private $_id;
	private $_name;
	public $course;
	
	public	function __construct($id,$name)
	{
		$this->_id=$id;
		$this->_name=$name;
		$this->course=new CourseCollection();
		$this->course->setLoadCallback('loadCourses',$this);
	}
	
	public function getName()
	{
		return $this->_name;
	}
	
	public function getID()
	{
		return $this->_id;
	}
	
	public function __toString()
	{
		return $this->_name;
	}
	public function loadCourses(Collection $col)
	{
		$col->addItem(new Course(1, "001", "语文"),1);
		$col->addItem(new Course(2, "002", "数学"),2);
	}
}
登入後複製
调用代码如下:

$student=new Student(1, "majiang");
print $student->getName();
print $student->course->getItem(1);


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

解決方法:您的組織要求您更改 PIN 碼 解決方法:您的組織要求您更改 PIN 碼 Oct 04, 2023 pm 05:45 PM

解決方法:您的組織要求您更改 PIN 碼

Windows 11 上調整視窗邊框設定的方法:變更顏色和大小 Windows 11 上調整視窗邊框設定的方法:變更顏色和大小 Sep 22, 2023 am 11:37 AM

Windows 11 上調整視窗邊框設定的方法:變更顏色和大小

如何在 Windows 11 上變更標題列顏色? 如何在 Windows 11 上變更標題列顏色? Sep 14, 2023 pm 03:33 PM

如何在 Windows 11 上變更標題列顏色?

OOBELANGUAGE錯誤Windows 11 / 10修復中出現問題的問題 OOBELANGUAGE錯誤Windows 11 / 10修復中出現問題的問題 Jul 16, 2023 pm 03:29 PM

OOBELANGUAGE錯誤Windows 11 / 10修復中出現問題的問題

Windows 11 上啟用或停用工作列縮圖預覽的方法 Windows 11 上啟用或停用工作列縮圖預覽的方法 Sep 15, 2023 pm 03:57 PM

Windows 11 上啟用或停用工作列縮圖預覽的方法

Windows 11 上的顯示縮放比例調整指南 Windows 11 上的顯示縮放比例調整指南 Sep 19, 2023 pm 06:45 PM

Windows 11 上的顯示縮放比例調整指南

10種在 Windows 11 上調整亮度的方法 10種在 Windows 11 上調整亮度的方法 Dec 18, 2023 pm 02:21 PM

10種在 Windows 11 上調整亮度的方法

如何在Safari中關閉iPhone的隱私瀏覽身份驗證? 如何在Safari中關閉iPhone的隱私瀏覽身份驗證? Nov 29, 2023 pm 11:21 PM

如何在Safari中關閉iPhone的隱私瀏覽身份驗證?

See all articles