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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀