我怎样才能简化这个PHP?
我有以下 PHP 模型函数。 我知道我在重复自己。
无论如何我可以简化这段代码吗?
function getTopMenus(){
$data[0] = 'root';
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['id']] = $row['name'];
}
}
$Q->free_result();
return $data;
}
function getheadMenus(){
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
function getrootMenus(){
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['id']] = $row['name'];
}
}
$Q->free_result();
return $data;
}
I have the following model functions with PHP.
I know I am repeating myself.
Is there anyway I can simplify this code?
function getTopMenus(){
$data[0] = 'root';
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['id']] = $row['name'];
}
}
$Q->free_result();
return $data;
}
function getheadMenus(){
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
function getrootMenus(){
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['id']] = $row['name'];
}
}
$Q->free_result();
return $data;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可以看到您可以尝试的一种简化,使用传递引用将事物分解为函数:
还可以使用 按引用传递 和 变量函数来分解中间的部分。可能会减少重复,但可能会也可能不会被视为“简化”。
编辑这就是我的意思。该代码未经测试。
I can see one simplification you might try, using pass-by-reference to factor things out into a function:
There's also the possibility of using pass-by-reference and variable functions to factor out the part in the middle. May reduce duplication, but may or may not be considered 'simplifying'.
EDIT Here's what I mean. This code is untested.
为什么不将参数传递到函数中并将它们放在“where”和“get”方法中?
Why not pass parameters into your function and place them in the 'where' and 'get' methods?
我不知道你的数据库和查询类是什么样的,但我会首先开始改进它们。将“array fetch”和“hash fetch”函数添加到查询类中:
使“db->where()”返回自身
一旦有了这个,您的客户端函数就会变得微不足道:
I don't know what your db and query classes look like, but i'd start improving these in the first place. Add "array fetch" and "hash fetch" functions to the query class:
Make 'db->where()' return itself
Once you have this, your client functions become trivial: