CodeIgniter从视图加载控制器 [英] CodeIgniter load controller from view

查看:124
本文介绍了CodeIgniter从视图加载控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从视图加载控制器?



这是我感到厌恶..
我想多次使用一个视图,但这个视图是由单独的控制器加载视图,信息从db.So becouse的信息从模型我不能只是设置 $ this-load-> view(); 等等是有办法做这件事,还是有更好的办法?

解决方案

我认为很多网站都面临类似的挑战,包括一个我正在加载相同的数据库内容到侧边栏几乎在网站的每一页。我用库和助手的组合实现了这一点:


  1. 将数据逻辑放入库中(我的名称为common.php) 。除了与数据库接口之外,您可能希望库将数据存储在本地变量中,以便在单个加载时多次引用它。

      public function get_total_items ()
    {
    if($ this - > _ total_items === NULL)
    {
    $ row = $ this-> ci-> db-> query (*)FROM items) - > row();
    $ this - > _ total_items = $ row [0];
    }
    return $ this - > _ total_items;
    }


  2. 创建助手以加载库。 (不要在视图中加载库!)我有MY_text_helper加载库并返回数据:

      function total_items()
    {
    $ CI =& get_instance();
    return $ CI-> common-> get_total_items();
    }


  3. 从视图中调用帮助函数。 p> < p>总项:<?php echo total_items(); > < / p>



Is there a way to load a controller from a view ?

Here is what i am affter.. I want to use one view multiple times, but this view is being loaded by separate controller that gives the view, information from the db.So becouse of that information from the model i can't just set $this-load->view(); and etc. Is there a way to do this thing, or it has a better way ?

解决方案

I think a lot of sites face similar challenges, including one I'm working on that loads the same db content into the sidebar on almost every page in the site. I implemented this with the combination of a library and a helper:

  1. Put the data logic into the library (mine is named common.php). In addition to interfacing with the database, you may want the library to store the data in a local variable in case you want to reference it multiple times on a single load.

    public function get_total_items()
    {
        if ($this->_total_items === NULL)
        {
            $row = $this->ci->db->query("SELECT COUNT(*) FROM items")->row();
            $this->_total_items = $row[0];
        }
        return $this->_total_items;
    }
    

  2. Create a helper to load the library. (Don't load libraries within a view!) I have MY_text_helper that loads the library and returns the data:

    function total_items()
    {
        $CI =& get_instance();
        return $CI->common->get_total_items();
    }

  3. Call the helper function from within the view.

    <p> Total items: <?php echo total_items(); ?> </p>

这篇关于CodeIgniter从视图加载控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆