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();
}
}
オブジェクト指向って便利だなあとありがたみを感じました。





