• yii 常用一些调用 (增加中)


    调用YII框架中 jqueryYii::app()->clientScript->registerCoreScript('jquery');    
      
    framework/web/js/sourcejs,其中registerCoreScript key调用的文件在framework/web/js/packages.php列表中可以查看
     
     view中得到当前controllerID方法 Yii::app()->getController()->id;      
     
     view中得到当前actionID方法 Yii::app()->getController()->getAction()->id;     
     
     yii获取ip地址 Yii::app()->request->userHostAddress;   
     
     yii判断提交方式 Yii::app()->request->isPostRequest  
     
    得到当前域名: Yii::app()->request->hostInfo   
     
     得到proteced目录的物理路径 YII::app()->basePath;     
     
     获得上一页的url以返回 Yii::app()->request->urlReferrer;  
     
     得到当前url Yii::app()->request->url;  
     
     得到当前home url Yii::app()->homeUrl  
     
     得到当前return url Yii::app()->user->returnUrl 
     
     项目路径 dirname(Yii::app()->BasePath) 
     
    项目目录 Yii::app()->request->baseUrl 只输出一个连接(url)<?php echo $this->createUrl('admin/left_menu');?> //**.php?r=admin/left_menu
    输出一组url(yii url 默认样式)
    <?php $this->widget('zii.widgets.CMenu',array(
                'items'=>array(
                    array('label'=>'主菜单', 'url'=>array('/admin/left_menu')),
                    array('label'=>'内容发布', 'url'=>array('/admin/page')),
                    array('label'=>'内容维护', 'url'=>array('/site/contact')),
                    array('label'=>'系统主页', 'url'=>array('/site/login')),
                    array('label'=>'网站主页', 'url'=>array('/site/logout')),
                    array('label'=>'会员中心', 'url'=>array('/site/login')),
                    array('label'=>'注销', 'url'=>array('/site/login')),
                ),
            )); ?>

    //除域名外的URL

    Yii::app()->request->getUrl();

    除域名外的首页地址

    Yii::app()->user->returnUrl;

    6、//除域名外的根目录地址 Yii::app()->homeUrl;

    YII FRAMEWORK的COOKIE使用方法

    设置cookie:

    [php] view plain copy
     
    1. $cookie = new CHttpCookie('mycookie','this is my cookie');  
    2. $cookie->expire = time()+60*60*24*30;  //有限期30天  
    3. Yii::app()->request->cookies['mycookie']=$cookie;  


    读取cookie:
    [html] view plain copy
     
    1. $cookie = Yii::app()->request->getCookies();  
    2. echo $cookie['mycookie']->value;  

    销毁cookie:
    [html] view plain copy
     
    1. $cookie = Yii::app()->request->getCookies();  
    2. unset($cookie[$name]);  

    在控制器添加CSS文件或JAVASCRIPT文件

     

    [php] view plain copy
     
    1. public function init()  
    2. {      
    3.     parent::init();      
    4.     Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/my.css');  
    5.     Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/css/my.js');  
    6. }  

    YII FRAMEWORK的用户验证与授权

    yii提供了CUserIdentity类,这个类一般用于验证用户名和密码的类.继承后我们需要重写其中的authenticate()方法来实现我们自己的验证方法.具体代码如下:

    [php] view plain copy
     
    1. class UserIdentity extends CUserIdentity  
    2. {  
    3.     private $_id;  
    4.     public function authenticate()  
    5.     {  
    6.         $record=User::model()->findByAttributes(array('username'=>$this->username));  
    7.         if($record===null)  
    8.             $this->errorCode=self::ERROR_USERNAME_INVALID;  
    9.         else if($record->password!==md5($this->password))  
    10.             $this->errorCode=self::ERROR_PASSWORD_INVALID;  
    11.         else  
    12.         {  
    13.             $this->_id=$record->id;  
    14.             $this->setState('title', $record->title);  
    15.             $this->errorCode=self::ERROR_NONE;  
    16.         }  
    17.         return !$this->errorCode;  
    18.     }  
    19.     public function getId()  
    20.     {  
    21.         return $this->_id;  
    22.     }  
    23. }  


    在用户登陆时则调用如下代码: 

    // 使用提供的用户名和密码登录用户
    [html] view plain copy
     
    1. $identity=new UserIdentity($username,$password);  
    2. if($identity->authenticate())  
    3.     Yii::app()->user->login($identity);  
    4. else  
    5.     echo $identity->errorMessage;  


    用户退出时,则调用如下代码: 


    [html] view plain copy
     
    1. // 注销当前用户  
    2. Yii::app()->user->logout();  

    其中的user是yii的一个components.需要在protected/config/main.php中定义
    [html] view plain copy
     
    1. 'user'=>array(  
    2.         // enable cookie-based authentication  
    3.         'allowAutoLogin'=>true,  
    4.         'loginUrl' => array('site/login'),  
    5. ),  



    YII FRAMEWORK中TRASACTION事务的应用

    [html] view plain copy
     
    1. $model=Post::model();  
    2. $transaction=$model->dbConnection->beginTransaction();  
    3. try  
    4. {  
    5.     // find and save are two steps which may be intervened by another request  
    6.     // we therefore use a transaction to ensure consistency and integrity  
    7.     $post=$model->findByPk(10);  
    8.     $post->title='new post title';  
    9.     $post->save();  
    10.     $transaction->commit();  
    11. }  
    12. catch(Exception $e)  
    13. {  
    14.     $transaction->rollBack();  
    15. }  

    Yii Framework中截取字符串(UTF-8)的方法

    Helper.PHP

    [php] view plain copy
     
    1. class Helper extends CController  
    2. {  
    3.         public static function truncate_utf8_string($string, $length, $etc = '...')  
    4.         {  
    5.             $result = '';  
    6.             $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');  
    7.             $strlen = strlen($string);  
    8.             for ($i = 0; (($i < $strlen) && ($length > 0)); $i++)  
    9.                 {  
    10.                 if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0'))  
    11.                         {  
    12.                     if ($length < 1.0)  
    13.                                 {  
    14.                         break;  
    15.                     }  
    16.                     $result .= substr($string, $i, $number);  
    17.                     $length -= 1.0;  
    18.                     $i += $number - 1;  
    19.                 }  
    20.                         else  
    21.                         {  
    22.                     $result .= substr($string, $i, 1);  
    23.                     $length -= 0.5;  
    24.                 }  
    25.             }  
    26.             $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');  
    27.             if ($i < $strlen)  
    28.                 {  
    29.                         $result .= $etc;  
    30.             }  
    31.             return $result;  
    32.         }  
    33. }  

    将Helper.php放进protectedcomponents文件夹下。

    使用方法:

    Helper::truncate_utf8_string($content,20,false);   //不显示省略号
    Helper::truncate_utf8_string($content,20);  //显示省略号 

    CBREADCRUMBS简介~俗称:面包屑

    功能介绍:zii.widgets 下的CBreadcrumbs类,其继承关系: CBreadcrumbs » CWidget » 
    CBaseController » CComponent .源代码位置: 
    framework/zii/widgets/CBreadcrumbs.php 
    面包屑类显示一个链接列表以表明当前页面在整个网站中的位置.
    由于面包屑通常会出现在网站的近乎所有的页面,此插件最好在视图的layout中进行部署.
    你可以定义一个breadcrumbs属性并且在布局文件中指派给(网站)基础控制器插件,如下所示:

    [html] view plain copy
     
    1. $this->widget('zii.widgets.CBreadcrumbs', array(  
    2.     'links'=>$this->breadcrumbs,  
    3. ));  

    于是乎,你需要时,只需要在每个视图脚本中,指定breadcrumbs属性(就可以显示出网页导航了).
    以上是官方提供的文档文件的介绍.
    下面介绍视图文件中写法:

    [html] view plain copy
     
    1. $this->breadcrumbs=array(  
    2.       'Users'=>array('index'),  
    3.       'Create',  
    4.      // 形式 :  'key' =>'value'  key的位置相当于最后显示出来的a标签内的名字, value则相当于a标签的href属性.  
    5.      // 'Create'表示当前页  故没有设置链接.  
    6. );  

    YII FRAMEWORK中验证码的使用

    1.在controller中修改:

    [html] view plain copy
     
    1. public function actions()  
    2. {  
    3.         return array(  
    4.         // captcha action renders the CAPTCHA image displayed on the contact page  
    5.                 'captcha'=>array(  
    6.                 'class'=>'CCaptchaAction',  
    7.                 'backColor'=>0xFFFFFF,  //背景颜色  
    8.                 'minLength'=>4,  //最短为4位  
    9.                 'maxLength'=>4,   //是长为4位  
    10.                 'transparent'=>true,  //显示为透明  
    11.         ),  
    12.         );  
    13. }  

    2.在view的form表单中添加如下代码:

    [html] view plain copy
     
    1. <?php if(CCaptcha::checkRequirements()): ?>  
    2. <div class="row">  
    3.     <?php echo $form->labelEx($model,'verifyCode'); ?>  
    4.     <div>  
    5.     <?php $this->widget('CCaptcha'); ?>  
    6.     <?php echo $form->textField($model,'verifyCode'); ?>  
    7.     </div>  
    8.     <div class="hint">Please enter the letters as they are shown in the image above.  
    9.     <br/>Letters are not case-sensitive.</div>  
    10.     <?php echo $form->error($model,'verifyCode'); ?>  
    11. </div>  
    12. <?php endif; ?>  


    YII FRAMEWORK的CHTML::LINK支持锚点

    CHtml::link('链接文字',array('article/view','id'=>'3','#'=>'锚名称');

    CUrlManager的 createUrl,是可以支持 '#' 的!

    $params = array('userid' => 100, '#' => '锚名称');
    $this->createUrl($route, $params);

    YII FRAMEWORK在WEB页面查看SQL语句配置

    [html] view plain copy
     
    1. 'components'=>array(  
    2.         'errorHandler'=>array(  
    3.         // use 'site/error' action to display errors  
    4.                 'errorAction'=>'site/error',  
    5.                 ),  
    6.         'log'=>array(  
    7.                 'class'=>'CLogRouter',  
    8.                 'routes'=>array(  
    9.                         array(  
    10.                                 'class'=>'CFileLogRoute',  
    11.                                 'levels'=>'error, warning',  
    12.                         ),  
    13.                         // 下面显示页面日志  
    14.                         array(  
    15.                                 'class'=>'CWebLogRoute',  
    16.                                 'levels'=>'trace',     //级别为trace  
    17.                                 'categories'=>'system.db.*' //只显示关于数据库信息,包括数据库连接,数据库执行语句  
    18.                         ),  
    19.                 ),  
    20.         ),  
    21. ),  


    YII FRAMEWORK打印AR结果

    [html] view plain copy
     
    1. $user = 模型->model()->findAll();  
    2. foreach($user $v) {  
    3.     var_dump($v->attributes);  
    4. }  

    yii 数据save后得到插入id

     
    $post->save();
    //得到上次插入的Insert id
    $id = $post->attributes['id'];
    如此很简单
     

    yii获取ip地址

    Yii::app()->request->userHostAddress;
     
     

    yii execute后获取insert id

    $id = Yii::app()->db->getLastInsertID();

    yii获取get,post过来的数据

    Yii::app()->request->getParam('id');
     
     

    yii如何设置时区

    可以在config/main.php 里'timeZone'=>'Asia/Chongqing',设定时区.

    yii如何将表单验证提示弄成中文的

    将main.php里的app配置加上language=>'zh_cn',系统默认的提示就是中文的了,要自定义消息就像楼上说的定义message

    yii如何获得上一页的url以返回

    Yii::app()->request->urlReferrer;

    yii多对多关联条件

    [html] view plain copy
     
    1. $criteria->addInCondition('categorys.id',$in);  
    2. $criteria->addSearchCondition('Shop.name',$keyword);$shops=Shop::model()->with(array('categorys'=>array('together'=>true)))->findAll($criteria);  
    同时要在Shop模型中加入alias='categorys' ,另外together=true放在模型的关联中也可
     

    yii如何防止重复提交?

    提交后Ccontroler->refresh();

    yii过滤不良代码

    [html] view plain copy
     
    1. $purifier=new CHtmlPurifier;  
    2. $purifier->options=array('HTML.Allowed'=>'div');  
    3. $content=$purifier->purify($content);  
    或者
    [html] view plain copy
     
    1. <?php $this->beginWidget('CHtmlPurifier'); ?>  
    2. ...display user-entered content here...  
    3. <?php $this->endWidget(); ?>  

    显示yii的sql语句查询条数和时间

    在config/main.php中配置在log组件的routes中加入
    [html] view plain copy
     
    1. array(  
    2. 'class'=>'CProfileLogRoute',  
    3. 'levels'=>'error, warning',  
    4. )  
    同时在db组件中加入'enableProfiling'=>true,同时在这种情况下,可以用CDbConnection::getStats() 查看执行了多少个语句,用了多少时间print_r(CDbConnection::getStats());
     

    Yii多数据库操作

    大多数情况下,我们都会采用同一类型的数据库,只是为了缓解压力分成主从或分布式形式而已。声明你可以在app config里声明其它的数据库连接:
    <?php
        ......
        'components'=>array(
            'db'=>....// 主链接
             'db1'=>...// 从连接1
            'db2'=>...// 从连接2
        )
        ......操作在代码里,可以通过Yii::app()->db1和Yii::app()->db2获得两个从连接。高级操作更高级(自动)的主从数据库功能将在1.1实现。
  • 相关阅读:
    ubuntu系统下安装最新版的MySQL
    scp本地服务器和远程服务器拷贝文件
    linux设置环境变量
    PHP程序员玩转Linux系列-lnmp环境的搭建
    nginx与负载均衡
    Linux下vim的常用命令总结
    nginx与location规则
    ssh秘钥对免密码登陆
    ubuntu下安装php pdo扩展和导入数据库
    ArrayList的删除实现
  • 原文地址:https://www.cnblogs.com/ylei11/p/6435682.html
Copyright © 2020-2023  润新知