2012-12-17 22 views
6

我已經添加在WP中的自定義插件(由我創建)在該插件我有類名爲BaseModel,它擴展wpdb。擴展wpdb在其他類 - 當使用get_results選擇給我空

這裏的問題是每當我嘗試運行查詢時,我得到false或null或空數組作爲結果。

class BaseModel extends wpdb{ 

public function __construct(){ 
    parent::__construct(DB_HOST, DB_USER, DB_PASS, DB_NAME); 
} 

function get_destinations($limit, $order){ 
    $query = "SELECT * FROM wp_relations"; 

    $result = $this->get_results($query, ARRAY_A); 
    var_dump($result); 
} 

function get_total_destinations(){ 
}} 

有人能告訴我什麼是錯?

謝謝。

+0

您確定數據庫憑證常量是否已定義? –

回答

5

其實它不是一個完整的OOP解決方案,但我通過將全局$ wpdb添加到我的函數來解決此問題。

class BaseModel { 


function get_destinations($limit, $order){ 
    global $wpdb; 
    $query = "SELECT * FROM wp_relations"; 

    $result = $wpdb->get_results($query, ARRAY_A); 
    var_dump($result); 
} 

function get_total_destinations(){ 
}} 

我希望你會覺得這有幫助。

2

More Info WordPress tests with wpdb

<?php 
class testWPDB extends wpdb { 
function prepare($query, $arguments){ 
     return vsprintf($query, $arguments); 
    } 
} 

class UTCW_Test_Data extends WP_UnitTestCase { 
protected $utcw; 
function setUp(){ 
    $this->utcw = UTCW_Plugin::get_instance(); 
} 

function getWPDBMock(){ 
    return $this->getMock('testWPDB', array('get_results'), array(), '', false); 
} 

function test_author(){ 
    $instance[ 'authors' ] = array(1, 2, 3); 
    $config = new UTCW_Config($instance, $this->utcw); 
    $db = $this->getWPDBMock('get_results'); 

    $db->expects($this->once()) 
    ->method('get_results') 
    ->with($this->stringContains('post_author IN (1,2,3)')); 

    $data = new UTCW_Data($config, $db); 
    $data->get_terms(); 
    } 
} 
0

我不認爲你想從它延伸?如果這個類將永遠在Wordpress文件中加載,那麼你將有權訪問全局$ wpdb。

class RandomClass { 

    private $wpdb = false; 

    public function __construct() { 
     global $wpdb; 

     if (is_object($wpdb)) { 
      $this->wpdb = $wpdb; 
     } 
    } 

    public function get_results($data) { 
     return $this->wpdb->get_results($data); 
    } 
}  
相關問題