分享

MVC之 控制器controller与视图view

 哇嘿嘿 2014-09-25
//在视图输出一个“hello world”字串
//controllers目录下创建一个HelloController,控制器的名字里要求用Controller结尾,首字母大写

class HelloController extends Controller{
  
    public function actionIndex(){
  
        //渲染一个视图
        $this->render('index');
    }
}
//在视图目录views下创建一个hello/index.php的文件,在文件里面输出hello world!

<?php
echo 'hello world';
?>


//     我们看到这个页面不仅仅只有hello world,还有头部导航和尾部,那他们是哪里来的呢

//我们进入render方法看看    

public function render($view,$data=null,$return=false)
    {
        //调用render前的钩子,在调用视图前的特殊处理逻辑可以在beforeRender里实现
        if($this->beforeRender($view))
        {
            //先获取renderPartial的输出结果,renderPartial是局部渲染,直接在action里调用效果如图2
            $output=$this->renderPartial($view,$data,true);
            //获取头尾部文件,这里是通过controller的layout属性来指定的
            if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
                $output=$this->renderFile($layoutFile,array('content'=>$output),true);
             
            $this->afterRender($view,$output);
  
            $output=$this->processOutput($output);
  
            if($return)
                return $output;
            else
                echo $output;
        }
    }

 
 

//     render是可以带参数的
//比如controller中定义一个变量$str

public function actionIndex(){
        $str = 'hello,world!';
        //渲染一个视图
        $this->render('index',array(
            'str'=>$str,
        ));
//        $this->renderPartial('index');
    }

//视图view中直接输出

<?php
echo 'hello world';
echo '<br />';
echo $str;
?>

//      视图中的$this是当前的控制器对象
//视图中可以用$this去调用controller的属性或者方法      

<?php
//调用控制器的属性
echo $this->id;
echo '<br />';
echo $this->action->id;
echo '<br />';
echo $this->layout;
echo '<br />';
  
//调用控制器里的方法
echo $this->createUrl('site/index');
?>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多