ITで遊ぶ

PHPのクラスの継承

PHPの紹介で、クラスの継承というとメソッドのオーバーライドの例しか見たことがない気がする。

ここんところCode Igniterでモデル(MVCでいうモデル)を作っていたが、データを暗号化する必要が出てきた。

こわごわ、メソッドを書いて読み取りの時は

parent::find_list($condition)

みたいな感じで、読み出してデータを復号する部分を書いた。
つまり、メソッドの継承。

書き込みの時は引数のデータを暗号化してから親のメソッドを呼んだらあっさりできてしまった。

コンストラクターの継承以外もできて当たり前だよな。

ただし、同名で継承したメソッドの引数は親と同じにしておかないとPHPに怒られる。

もともとCoge Igniterでモデルクラスを書く時は、DBの基本的なアクセスを実装したMY_Model.phpをcoreに入れて継承して使っているんだけど。(モデル名をデフォルトでテーブル名とみなすのがミソ)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// implemented basic database access.

class MY_Model extends CI_Model{
	protected $_table;
	
	public function __construct(){
		parent::__construct();
		$this->_table = strtolower(get_Class($this)) ;
		// $this->load->database(); autoload
	}

	public function count($conditions=NULL, $tablename=""){
		if($tablename==""){
    		$tablename=$this->_table;
    	}
		if ($conditions != NULL){
			$this->db->where($conditions);
		}
		$this->db->from($tablename);
		return $this->db->count_all_results();
	}
	
	public function find_list($conditions=NULL,$tablename="", $limit = 100, $offset=0){
		if($tablename==""){
    		$tablename=$this->_table;
    	}
    	if ($conditions !=NULL){
    		$this->db->where($conditions);
    	}
		$query = $this->db->get($tablename,$limit,$offset);
		return $query->result();	
	}
	
	public function find_first($conditions=NULL, $tablename=""){
		if($tablename==""){
    		$tablename=$this->_table;
    	}
		if ($conditions != NULL){
			$this->db->where($conditions);
		}
		$query = $this->db->get($tablename);
		return $query->first_row();
	}	
    function insert($data,$tablename=""){
    	if($tablename==""){
    		$tablename=$this->_table;
    	}
    	$this->db->insert($tablename,$data);
    	return $this->db->affected_rows();
    }	

    function update($data,$conditions,$tablename=""){
    	if ($tablename==""){
    		$tablename=$this->_table;
    	}
    	$this->db->where($conditions);
    	$this->db->update($tablename,$data);
    	return $this->db->affected_rows();
    }

    public function delete($conditions, $tablename=""){
    	if ($tablename==""){
    		$tablename = $this->_table;
    	}
    	$this->db->where($conditions);
    	$this->db->delete($tablename);
    	return $this->db->affected_rows();

    }
}

オブジェクト指向って便利だなあとありがたみを感じました。

関連記事

  1. :MOVE miniバギーカー

  2. CakePHP(1)

  3. 省電力一定時間点滅 スイッチ付プログラム

  4. カラーミーAPIを使う(発送データ作成)

  5. PHP, Python, Ruby, バランス

  6. Zend Framework

  7. Windowsスクリプト

  8. CodeIgniterでGoogleChartを使う

記事をプリント