2014-01-07 37 views
1

我是CodeIgniter中的新成员。我想在一个单独的类函数中执行所有数据库查询,只是为了重用能力。 与JAVA春季框架相同。如何在Codeigniter的独立类函数中执行SQL查询

例如:我需要不同控制器中所有用户的列表。为此,在单独的Class Function中写入getAllUser()的查询。从那以后,我可以从不同的控制器

这是一段代码,我想实现我的目标称之为

这将是我服务类

class UserManagementServices extends CI_Controller { 
    public static function getAllUsers(){ 
     $this->load->database(); 
     return $this->db->query("SELECT * FROM users"); 
    } 
    public static function getUser($userId){ ... } 
    public static function removeUser($userId){ ... } 
    public static function getUserHistory($userId){ ... } 
} 

这将是我的控制器类

class User extends CI_Controller { 
    public function index(){ 
     $this->load->view('userHome'); 
    } 
    public function viewAllUser(){ 
     include 'application/controllers/UserManagementService.php'; 
     var_dump(UserManagementService::getAllUsers()); 
    } 
} 

但是这段代码不起作用。

在CodeIgniter它不允许我在静态方法中执行查询。 当我想这

class UserManagementServices extends CI_Controller { 
    public static function getAllUsers(){ 
     return 'Testing Purpose...'; 
    } 
} 

,它工作正常。

+0

这是模型的用途。把这些放入模型中,而不是控制器。 http://ellislab.com/codeigniter/user-guide/general/models.html –

+0

我可以在这种情况下做什么。如果我的查询包含多个联接 'SELECT * FROM USER,USER_LOG,USER_ROLE,国家,城市 WHERE USER.USER_ID = USER_LOG.USER_ID AND USER.USER_ID = USER_ROLE.USER_ID AND USER.CITY_ID =城市。CITY_ID AND CITY.COUNTRY_ID = COUNTRY.COUNTRY_ID' – UFFAN

+0

建立模型函数以运行该查询?我不明白你在问什么。 –

回答

1

最后我找到了解决方案。我们如何可以执行SQL查询笨库

里面以下是我笨库类

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 
class UserManagementService { 
    private $ciInstance; 
    function __construct(){ 
     $this->ciInstance =& get_instance(); 
     $this->ciInstance->load->database(); 
    } 
    public function getAllUsers(){ 
     $query ="SELECT * FROM USERS"; 
     return $this->ciInstance->db->query($query);  
    } 
} 

的代码这是我笨控制器类

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 
class Home extends CI_Controller { 
    public function index(){ ... } 
    public function viewAllUsers(){ 
     // .... some piece of code here .... 
     $this->load->library('usermanagementservice'); 
     $users = $this->usermanagementservice->getAllUsers(); 
     // .... some piece of code here .... 
    } 
} 

我张贴,因为。可能会对别人有帮助

4

首先,静态方法没有任何CI可用的东西。因此,使用数据库做一些事情将不会从那里开始。其次,CI中的控制器通常映射到URI,所以最好仅以这种方式使用它们。

如果你有一些可重用的代码,那么创建一个帮助程序或库就是你需要的。您将它们存储在单独的文件夹中,然后可以加载库,例如,如下所示:$this->load->library('class_name');然后像这样访问它们:$this->class_name->method();

虽然这不适用于您的数据库。数据访问由您的模型处理(duh)。您可以使用与库类似的方式创建它们,并在CI文档中对此进行了很好的说明,您应该阅读:http://ellislab.com/codeigniter/user-guide/index.html

+0

我在库'$ this-> load-> library('database');'和'$ this-> load-> database();'中使用了两种方法来加载数据库,但它不起作用。 – UFFAN