duanqiaoren9975 2013-04-24 15:21
浏览 22
已采纳

如何将函数从PHP Procedural转换为PHP MVC?

I have this function on my View Page, which truncates some data to present it on my table.

function truncate($mytext) {  
    //Number of characters to show  
    $chars = 100;  
    $mytext = substr($mytext,0,$chars);  
    $mytext = substr($mytext,0,strrpos($mytext,' '));    
    return $mytext;  
    }  

I set a local variable for my dynamic text:

$mydescription = $value['PROBLEM_DESCRIPTION']

On the same page, I have this:

echo '<td><p>' .truncate($mydescription). '; ?></p><</td>

And it works perfect, so my question is how can apply this on an MVC architecture using Codeigniter? If somebody has an idea let me know, thanks!!!

  • 写回答

5条回答 默认 最新

  • douchong4730 2013-04-24 15:29
    关注

    You could do it in the controller:

    class Something extends CI_Controller{
        public function index(){
            $data['mytext'] = $this->_truncate('some text to truncate');
    
            //truncated text will be available in the view as $mytext
            $this->load->view('some_view', $data);
        }
    
        private function _truncate($text = NULL){
            if($text){
                $chars = 100;  
                $mytext = substr($text,0,$chars);  
                $mytext = substr($text,0,strrpos($text,' ')); 
                return $mytext;
            }  
        }
    }
    

    Edit:

    You are calling db stuff in your view which is entirely not Codeigniter MVC.

    This is what it might look like in MVC:

    Controller

    class Something extends CI_Controller{
        public function index(){
            $test_text = $this->my_model->get_text();
            $data['test_text'] = $this->_truncate($test_text);
    
            //truncated text will be available in the view as $test_text
            $this->load->view('some_view', $data);
        }
    
        private function _truncate($text = NULL){
            if($text){
                $chars = 100;  
                $mytext = substr($mytext,0,$chars);  
                $mytext = substr($mytext,0,strrpos($mytext,' ')); 
                return $mytext;
            }  
        }
    }
    

    Model

    class My_Model extends CI_Model{
    
        public function get_text(){
            //$this->db->get_where....or other db functions
            return "testing text... this is only a test";
        }
    
    }
    

    View

    <html>
    <body>
    <b><?php echo $test_text; ?></b>
    </body>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛