Codeigniter 2 在循环中使用库
我有一个一直碰壁的问题,我需要一些关于解决这个问题的最佳方法的建议。
我有一个循环从我的模型中获取数据,但在该循环中,我必须根据库对其进行验证,但我似乎找不到一个好的方法来做到这一点。
例如,我有一个看起来与此类似的模型方法:
public function GetUserList() {
$this->db->select('username, email, joindate, rank')->from('user');
$query = $this->db->get();
//loop through data and bind to an array.
foreach ($query->result() as $row) {
$users[] = $row;
}
return $users;
}
当页面加载时,用户将看到用户列表及其信息,但有些用户不希望显示他们的电子邮件地址,然后我们必须使用用户库来获取该用户的设置,并查看我们是否应该隐藏该电子邮件。
我发现的唯一解决方案是使用辅助函数作为绕道,但我觉得这会在将来重复类似的事情时困扰我。
我发现的另一个问题是,一旦您创建了库,它就不会将对象作为新对象重新启动(就像在普通 PHP 中一样)。
我希望有人能有一个好的方法来解决这样的挫折。
最后一项,如果有影响的话,我也使用 Twig 来处理我的观点。
I have an issue I keep hitting the wall on and I need some suggestions on the best way around this.
I got a loop that grabs data from my model, but within that loop, I have to validate it against a library, but I cant seem to find a good way to do that.
for example, I got a model method that looks similar to this:
public function GetUserList() {
$this->db->select('username, email, joindate, rank')->from('user');
$query = $this->db->get();
//loop through data and bind to an array.
foreach ($query->result() as $row) {
$users[] = $row;
}
return $users;
}
when the page loads the user will see a list of users and their info, but some users don't want their email address to be shown, we then have to use the user library to fetch the settings for that user and see if we should hide that email or not.
the only solution i found was to use a helper function as a detour, but I feel that is going to bite me in the future duplicating things like that.
the other issue I found was once you created the library it didn't restart the object as a new one (like it would in vanilla PHP).
I'm hoping someone has a good way to resolve a setback like this.
One last item, if it makes a difference, I'm also using Twig to handle my views.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要使用
load()
函数加载每个库文件。load()
函数用于加载全局 (CI) 命名空间中的单个实例。如果您想使用对象集合,您应该像在 PHP 中通常那样require
文件。You do not need to load every library file using the
load()
function. Theload()
function is for loading a single instance in the global (CI) namespace. If you want to work with a collection of objects, you shouldrequire
the file like you normally would in PHP.如果可能的话,我会亲自加入您的偏好表。这样您就不必为每个用户执行单独的查询。
I would personally join on your preferences table if possible. That way you wouldn't have to do a separate query for every single user.