七、MVC之 控制器controller与视图view

在视图输出一个“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;
        }
    }
图2:renderPartial的输出结果,是不带有头部和尾部的


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');
?>

转载于:https://my.oschina.net/lonxom/blog/168238

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值