php框架

 首页 > php框架 > YII > YII Framework学习教程-YII的C-控制器

YII Framework学习教程-YII的C-控制器

分享到:
【字体:
导读:
          设计模式中,MVC结构是使用最多的。现在大部分PHP框架的必备标准就是拥有MVC模式。这是最基本的要求。如果不具备这个要求,就不能称之为框架,只能说是一个工具类集合。M-V-C中是...

      设计模式中,MVC结构是使用最多的。现在大部分PHP框架的必备标准就是拥有MVC模式。这是最基本的要求。如果不具备这个要求,就不能称之为框架,只能说是一个工具类集合。M-V-C中是控制器,可以认为是MVC结构的核心,调度者,像一个国家的领导人。大部分程序的实现还是在此部分,(如果没有涉及的很多数据逻辑的时候,因为对数据库的访问操作,我们大部分都可以用YII提供的功能实现,绝大部分无非就是CRUD。),所以你的MVC中C的代码决定了你的代码的质量。你的水平也可以通过C层的代码来衡量。当然这不是绝对的。

    MVC结构中action也是很重要的角色。

    控制器C的功能其实是action实现的。所以C如果是是领导人。那么他内部的action可以认为是一个个的政府官员。所以action决定了这个国家的。。。。aciton的所作所为,他的好坏决定了整个政府体系的好坏。所以作为一个aciton要做好自己的职责。为人民服务。

    

     来看看YII中C的规则:

     C类文件的存放位置以及规范:

     一般是在protected/controllers文件夹中。如果你的框架中存在modules.就位于/protected/modules/模块名称/controllers下面

    

      C类的文件名通常是一Controller.php结尾。的前面是你的类名。例如TestController.php。Test就是控制器的名称。如果是TestTestController.php,注意了默认的访问的时候的路由是第一个字母变为小写其他的保持不变。即http://www.localyii.com/testwebap/index.php?r=testTest。 对应View中文件夹应该为testTest和默认路由保持一直。所以C类的名称大小写敏感。并且敏感到VIew层。

 

 

   C类的结构

1.必须extends Controller或者CController

2.类名一般和文件名保持一直必须一Controller结尾。

 

[php] view plaincopy
 
  1.   
  2.   
  3. class UserController extends Controller  
  4. {  
  5. }  

如果看文档是用的

 

 

[php] view plaincopy
 
  1. class SiteController extends CController  
  2. {  
  3. }  

 

 CController和Controller的关系是什么

看看代码

 

[php] view plaincopy
 
  1. /** 
  2.  * Controller is the customized base controller class. 
  3.  * All controller classes for this application should extend from this base class. 
  4.  */  
  5. class Controller extends CController  
  6. {  
  7.     /** 
  8.      * @var string the default layout for the controller view. Defaults to '//layouts/column1', 
  9.      * meaning using a single column layout. See 'protected/views/layouts/column1.php'. 
  10.      */  
  11.     public $layout='//layouts/column1';  
  12.     /** 
  13.      * @var array context menu items. This property will be assigned to {@link CMenu::items}. 
  14.      */  
  15.     public $menu=array();  
  16.     /** 
  17.      * @var array the breadcrumbs of the current page. The value of this property will 
  18.      * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links} 
  19.      * for more details on how to specify this property. 
  20.      */  
  21.     public $breadcrumbs=array();  
  22. }  


 

可以看到他们之间的关系。看看注释就知道了他们直接的区别。可以认为Controller是CController边角料,实质上还是CController是做主要工作的。不信可以找到CController类的实现代码看看,就发现了。这里用Controller,毕竟可以少些一个字母。

下面看看控制器的内部的结构,打开SiteController.php文件

 

[php] view plaincopy
 
  1.   
  2. class SiteController extends Controller  
  3. {  
  4.     /** 
  5.      * Declares class-based actions. 
  6.      */  
  7.     public function actions()  
  8.     {  
  9.         return array(  
  10.             // captcha action renders the CAPTCHA image displayed on the contact page  
  11.             'captcha'=>array(  
  12.                 'class'=>'CCaptchaAction',  
  13.                 'backColor'=>0xFFFFFF,  
  14.             ),  
  15.             // page action renders "static" pages stored under 'protected/views/site/pages'  
  16.             // They can be accessed via: index.php?r=site/page&view=FileName  
  17.             'page'=>array(  
  18.                 'class'=>'CViewAction',  
  19.             ),  
  20.         );  
  21.     }  
  22.   
  23.     /** 
  24.      * This is the default 'index' action that is invoked 
  25.      * when an action is not explicitly requested by users. 
  26.      */  
  27.     public function actionIndex()  
  28.     {  
  29.         // renders the view file 'protected/views/site/index.php'  
  30.         // using the default layout 'protected/views/layouts/main.php'  
  31.         $this->render('index');  
  32.     }  
  33.   
  34.     /** 
  35.      * This is the action to handle external exceptions. 
  36.      */  
  37.     public function actionError()  
  38.     {  
  39.         if($error=Yii::app()->errorHandler->error)  
  40.         {  
  41.             if(Yii::app()->request->isAjaxRequest)  
  42.                 echo $error['message'];  
  43.             else  
  44.                 $this->render('error'$error);  
  45.         }  
  46.     }  
  47.   
  48.     /** 
  49.      * Displays the contact page 
  50.      */  
  51.     public function actionContact()  
  52.     {  
  53.         $model=new ContactForm;  
  54.         if(isset($_POST['ContactForm']))  
  55.         {  
  56.             $model->attributes=$_POST['ContactForm'];  
  57.             if($model->validate())  
  58.             {  
  59.                 $headers="From: {$model->email}rnReply-To: {$model->email}";  
  60.                 mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);  
  61.                 Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');  
  62.                 $this->refresh();  
  63.             }  
  64.         }  
  65.         $this->render('contact',array('model'=>$model));  
  66.     }  
  67.   
  68.     /** 
  69.      * Displays the login page 
  70.      */  
  71.     public function actionLogin()  
  72.     {  
  73.         $model=new LoginForm;  
  74.   
  75.         // if it is ajax validation request  
  76.         if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')  
  77.         {  
  78.             echo CActiveForm::validate($model);  
  79.             Yii::app()->end();  
  80.         }  
  81.   
  82.         // collect user input data  
  83.         if(isset($_POST['LoginForm']))  
  84.         {  
  85.             $model->attributes=$_POST['LoginForm'];  
  86.             // validate user input and redirect to the previous page if valid  
  87.             if($model->validate() && $model->login())  
  88.                 $this->redirect(Yii::app()->user->returnUrl);  
  89.         }  
  90.         // display the login form  
  91.         $this->render('login',array('model'=>$model));  
  92.     }  
  93.   
  94.     /** 
  95.      * Logs out the current user and redirect to homepage. 
  96.      */  
  97.     public function actionLogout()  
  98.     {  
  99.         Yii::app()->user->logout();  
  100.         $this->redirect(Yii::app()->homeUrl);  
  101.     }  
  102. }  
 

 

3.action方法的的规范可以从上述代码中看到。就是以action开头。然后是action的具体名称
 

  类中有一个actions方法。看具体代码

 

[php] view plaincopy
 
  1. /** 
  2.      * Declares class-based actions. 
  3.      */  
  4.     public function actions()  
  5.     {  
  6.         return array(  
  7.             // captcha action renders the CAPTCHA image displayed on the contact page  
  8.             'captcha'=>array(  
  9.                 'class'=>'CCaptchaAction',  
  10.                 'backColor'=>0xFFFFFF,  
  11.             ),  
  12.             // page action renders "static" pages stored under 'protected/views/site/pages'  
  13.             // They can be accessed via: index.php?r=site/page&view=FileName  
  14.             'page'=>array(  
  15.                 'class'=>'CViewAction',  
  16.             ),  
  17.         );  
  18.     }  

 

 

 

[php] view plaincopy
 
  1.    public function actions()  
  2. {  
  3.     // return external action classes, e.g.:  
  4.     return array(  
  5.         'action1'=>'path.to.ActionClass',  
  6.         'action2'=>array(  
  7.             'class'=>'path.to.AnotherActionClass',  
  8.             'propertyName'=>'propertyValue',  
  9.         ),  
  10.     );  
  11. }  


 

 


[php] view plaincopy
 
  1. public function createAction($actionID)  
  2.     {  
  3.         if($actionID==='')  
  4.             $actionID=$this->defaultAction;  
  5.         if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method  
  6.             return new CInlineAction($this,$actionID);  
  7.         else  
  8.         {  
  9.             $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);  
  10.             if($action!==null && !method_exists($action,'run'))  
  11.                 throw new CException(Yii::t('yii''Action class {class} must implement the "run" method.'array('{class}'=>get_class($action))));  
  12.             return $action;  
  13.         }  
  14.     }  
  15.     protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())  
  16.     {  
  17.         if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))  
  18.         {  
  19.             $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);  
  20.             return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);  
  21.         }  
  22.         else if($pos===false)  
  23.             return null;  
  24.         // the action is defined in a provider  
  25.         $prefix=substr($actionID,0,$pos+1);  
  26.         if(!isset($actionMap[$prefix]))  
  27.             return null;  
  28.         $actionID=(string)substr($actionID,$pos+1);  
  29.         $provider=$actionMap[$prefix];  
  30.         if(is_string($provider))  
  31.             $providerType=$provider;  
  32.         else if(is_array($provider) && isset($provider['class']))  
  33.         {  
  34.             $providerType=$provider['class'];  
  35.             if(isset($provider[$actionID]))  
  36.             {  
  37.                 if(is_string($provider[$actionID]))  
  38.                     $config=array_merge(array('class'=>$provider[$actionID]),$config);  
  39.                 else  
  40.                     $config=array_merge($provider[$actionID],$config);  
  41.             }  
  42.         }  
  43.         else  
  44.             throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));  
  45.         $class=Yii::import($providerType,true);  
  46.         $map=call_user_func(array($class,'actions'));  
  47.         return $this->createActionFromMap($map,$actionID,$requestActionID,$config);  
  48.     }  

主要功能:

1.可以把action的功能放到一个单独的类文件中,这里就是可来绑定action和action的具体类文件。可以不action写到外部,其他的框架应该没这个功能。

 例如。

自带的验证码的例子,生成验证码

http://www.localyii.com/testwebap/index.php?r=site/captcha

自定义例子

目录结构

├── controllers
│   ├── post
│   │   └── UpdateAction.php
│   ├── SiteController.php
│   ├── TestTestController.php
│   └── UserController.php

文件TestTestController.php

 

[php] view plaincopy
 
  1. public function actions()  
  2. {  
  3.     // return external action classes, e.g.:  
  4.     return array(  
  5.         'update'=>'application.controllers.post.UpdateAction',  
  6.     );  
  7. }  

 

 

 文件UpdateAction.php

 

 

 

[php] view plaincopy
 
  1. class UpdateAction extends CAction {  
  2.     public function run() {  
  3.         exit('Test1 ,run  update action') ;  
  4.     }  
  5. }  

访问

 

http://www.localyii.com/testwebap/index.php?r=testTest/update

 

会看到打印如下结果

Test1 ,run update action

 

 

大体对控制器和action的使用有所了解了。具体的还需要慢慢写代码体会。具体的细节也需也自己在代码中学习理解。这里只是简单的例子。

 
分享到:
YII公用控制器_yii控制器共继承
如果你的项目中有控制器需要共用,其实只需要在config/main.php中加入一小段代码即可实现: XML/HTML代码 'controllerMap'=>array(       'xxx'=>'ext.XxxController'   ),   然后就可以直接调用了:index.php?r=xxx/index,即可以调用Xx...
Yii使用公共函数
在网站项目中,没必要把公用的函数写成一个工具类,有时候面向过程其实更方便。 在入口文件index.php里添加 require_once('protected/function.php'); 即可对其引用,成为公用的函数集合。 function.php如下:  
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……