2013-08-24 23 views
0

我必须使用旧数据库驱动程序(ora_logon),而不是cakephp支持使用Oracle数据库。我不能使用oci驱动程序。如何使用cakephp 2与自定义数据库连接和原始查询

现在我做如下: 每个模型的每个方法连接到数据库和retrive数据

class SomeClass extends Model { 
    public function getA(){ 
     if ($conn=ora_logon("username","password"){ 
      //make the query 
      // retrive data 
      //put data in array and return the array 
     } 
    } 

    public function getB(){ 
     if ($conn=ora_logon("username","password"){ 
      //make the query 
      // retrive data 
      //put data in array and return the array 
     } 
    } 
} 

我知道这是不是最好的方法去。 我怎么能离开cakephp管理打开和关闭数据库的连接,并让模型只回收数据?我对任何数据库抽象层不感兴趣。谢谢

回答

0

我想你可以做出自己的OracleBehavior。每个模型都可以使用这种行为,并且可以在其中覆盖或扩展模型的find()行为,以构建传统的oracle查询并运行它(我对Oracle不太了解)。

然后,在您的行为beforeFind()中,您可以打开您的连接,并在行为afterFind()中关闭数据库连接。

这样,每次查询运行前,它都会自动打开连接,并且每次查找后都会关闭它。你可以用beforeSave()和afterSave()和beforeDelete()和afterDelete()来做同样的事情。 (你可能会希望创造行为的单一connect()方法和disconnect()方法,所以您不必重复代码在每个beforeX()方法。

0

真的需要扩展蛋糕模型类?

class SomeClass extends Model { 
    private $conn; 
    public function constructor() { 
     parent::constructor(); 
     $conn = ora_logon("username","password"); 
     if(!$conn) 
      throw new Exception(); 
    } 

    public function getA() { 
     //Some code 
    } 
} 

SomeController:

App::uses('SomeClass','Model'); 

public function action() { 
    $data = array(); 
    $error = null; 
    try{ 
     $myDb = new SomeClass(); 
     $data = $myDb->getA(); 
    } catch($e) { 
     $error = 'Cannot connect to database'; 
    } 
    $this->set(compact('data', 'error')); 
}