免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3123 | 回复: 1
打印 上一主题 下一主题

Yii框架tips 2。。。。。。。。。。。 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-01-10 15:47 |只看该作者 |倒序浏览
Yii框架tips 2。。。。。。。。。。。










4、在view中用CGridView显示
设置好
<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
),
)); ?>
以上代码大部分是yii自动生成的,只要做少量修改即可
有时候会出现,搜索后页面为空的清况,原因可能是
layout/main.php中
echo $content外层无div,就是说main.php中必须有一个div包含$content
//CListView详解
其用列表的形式显示数据,不象CGridView一样,用表格显示数据,CListView用一个 view模板来显示每一条数据
其支持排序与分页
常用的代码如下
<?php
$dataProvider = new CActiveDataProvider('Post',array(
'pagination'=>array(
'pageSize'=>2
),
));
$this->widget('zii.widgets.CListView',array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'template'=>' {summary} {items} {pager}{sorter}',
'sortableAttributes'=>array(
'title',
'create_time'=>'Post Time',
),
));



CActiveForm详解
快速生成表单,支持ajax验证,对于比较复杂的验下最好是自己生成表单,写验证方法
常用代码,在Controller中
public function actionForm()
{
$post = new Post();
if(isset($_POST['ajax']) && $_POST['ajax']==='post'){
echo CActiveForm::validate($post);
Yii::app()->end();
}
if(isset($_POST['Post'])){
$post->attributes = $_POST['Post'];
if($post->save()){
echo '存成功了';
}
}
$this->render('form',array('post'=>$post));
}
在view中
<?php
$form = $this->beginWidget('CActiveForm',array(
'id'=>'post',//这里与Controller中的ajax对应
'enableAjaxValidation'=>true,
));
?>
<?php echo CHtml::errorSummary($post); ?>
<?php echo $form->labelEx($post,'title');?>
<?php echo $form->textField($post,'title')?>
<?php echo $form->error($post,'title'); ?> error一定要写上,要不不会触发ajax验证
<?php echo $form->labelEx($post,'content');?>
<?php echo $form->textField($post,'content')?>
<?php echo CHtml::submitButton($post->isNewRecord ? 'Create' : 'Save'); ?>
<?php $this->endWidget(); ?>
//CBreadcrumbs常用代码
<?php $this->widget('zii.widgets.CBreadcrumbs', array(
'links'=>$this->breadcrumbs,
'homeLink'=>'<span><a href="http://abc.com">shouye</a></span>',
'separator'=>'>>>'
)); ?>
其中breadcrumbs中Controller中的一个属性,如果要出现导航,就要在view中给此属性附值
生成的html如下
<div class="breadcrumbs">
<span><a href="http://abc.com">shouye</a>
</span>&gt;&gt;&gt;<span>Managde Posts</span>&gt;&gt;&gt;
<span>b</span>&gt;&gt;&gt;<span>c</span></div>
所以如果网站用到导航的时候,美工最好把导航代码定义如上
//CDetailView 用在仅仅是为了查看数据时,还是比较有用的,比如用在后台


如何在提交后显示一段提示
在控制器中
if(isset($_POST['name'])){
Yii::app()->user->setFlash('success','you are success');
$this->refresh();
}
在view中
if (Yii::app()->user->hasFlash('success')){
echo 're is'.Yii::app()->user->getFlash('success');
}else{
echo 'no';
}


如何得到当前域名
app()->request->hostInfo


activeDropDownList,给出提示,并有值
array('empty'=>array(0=>'选择分组')
<input type="submit" class="btn" value="提交" />


验证码如何生成及验证
Controller中
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
'maxLength'=>4,
'minLength'=>4,
),
);
}
View中
<?php echo CHtml::activeTextField($user, 'verifyCode');?>
<?php $this->widget('CCaptcha',array(
'captchaAction' => '/site/captcha',
'showRefreshButton' => false,
'clickableImage' => true,
'imageOptions' => array('align'=>'top', 'title'=>'重新获取'),
));?>
Model中
array('verifyCode', 'captcha', 'captchaAction'=>'site/captcha', 'message' => '输入的验证码不正确'),
set_time_limit(0);//禁止角本超时


如何想把手工的东西记录的数据库
main.php中配置log
array(
'class'=>'CDbLogRoute',
'levels'=>'info',
'logTableName'=>'Log',
'connectionID'=>'db',
),
应用时
Yii::log('信息','info');
deleteAllByAttributes(array("phone"=>$phones)直接接受一个数组,可以删除数组中符合条件的记录
YII_BLOG STUDY重新看了一遍yii blog,有些记录会与上边的重复
YII:Trace() 在debug模式是才记录信息,同时在main.php中的Log中的配置中的levels中要有trace,至于记录多少
栈由index.php中的YII_TRACE_LEVEL决定


配置Gii
'modules'=>array(
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'123',
),
),


获得客户端IP
if($_SERVER['HTTP_CLIENT_IP']){
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif($_SERVER['HTTP_X_FORWARDED_FOR']){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip = $_SERVER['REMOTE_ADDR'];
}


CActiveForm还是比较强大的,建议在以后的项目中form都用这个来实现
layout/中的视图是可以继承的
<?php $this->beginContent('/layouts/main'); ?>
然后在中间出现$content即可
<?php $this->endContent(); ?>
create,update最好是分开放在两个action中,共用一个form,中间可以加一层view,以在头尾显示不同的东西
成段的完成一个功能的代码尽量拿出来放到一个方法中
$this->beginWidget('CMarkdown', array('purifyOutput'=>true));
echo $data->content;
$this->endWidget();
linkButton,在删除时需要用js提示,可以看下这此组件中的comfirm
而且他们的提交方式都是post,是因为在jquery.yii.js写死了
具体的以在源文件中低部找到那段js中的ajaxsubmit,所在的js看下
filter是在执行action之前或之后执行的一段代码,要应用filters必须得写
CController::filters()方法
为什么在filters方法写上
return array(
'accessControl', // perform access control for CRUD operations
);能进行crud验证呢?
accessController是CContronller内置的filter,其调用
accessRules,得到验证规定,所以也要重写对应的accessRules,返回一个验证规则的数组成部分
if the application uses modules,
a root alias is also predefined for each module ID and refers to the base path of the corresponding module
如:echo YiiBase::getPathOfAlias('bbs');得到module bbs的路径
关于CUrlManager
'模式'=>'route'
matchValue是指,对于一个url规则,正常情况下是只看参数的名子是否一样就应用规则
如果matchValue=true,则也要看值
如,规则
'index-/<id:\d+>'=>array("book/index",'matchValue'=>false),
$this->createUrl('book/index', array('id'=>'abcd'));可以应用以上规则的,
如果规则中的matchValue=true,则就不能应用了
XSS又叫CSS (Cross Site Script) ,跨站脚本攻击。
它指的是恶意攻击者往Web页面里插入恶意html代码,当用户浏览该页之时,
嵌入其中Web里面的html代码会被执行
renderPartial()
render()
后者会把需要的js,css等嵌入
前者可以通过把最后一个参数设置成true完成一样的功能
addInCondition 不用考虑数组是空的情况yii会自动处理
如何得到当前url?
Yii::app()->request->url;
ctype_开始的几个函数,用于检查字任串是不是符合要求,代替了简单的正则表达式
CController中的setPageState可以保存同一页中的POST的表单状态
如何通过BEhavior修改CActiveRecord?
写类文件继承自
class LLog extends CActiveRecordBehavior{
public function beforeDelete($event){
$model = get_class($this->Owner);
//做要做的事,比如日志或修改模型字段内容
}
}
然后修改模型文件
public function behaviors()
{
return array(
// Classname => path to Class
'LLog'=>'application.behavior.LLog',
);
}
如何在应用程序处理请求之前执行一段操作?
在main.php中配置
'onBeginRequest' => 'function'
当然这个function方法要存在
也可以写在放口文件index.php中,代码改成如下
$app = Yii::createWebApplication($config);
$app->onbeginRequest = 'begin';
$app->run();
function begin(){
echo 'yyyyydddyyyyyy';
}
为什么在CActiveRecordBehavior中用
beforesave就可以代表了事件onBeforeSave
注意基为中最上边的events方法中返回的对应关系
'onBeforeSave'=>'beforeSave'
在调用attacth(CBehavior中)的时候,
$owner->attachEventHandler($event,array($this,$handler));
就指定了事件onBeforeSave的处理函数是用本类中的beforeSave
YII中的CComponent,CEvent与Behavior及CActiveRecordBehavior个人理解
这一块教程少,今天个人理解了下,写了个小例子,有助于理解
完成如下功能,一个JTool类,继承CComponent,当其长度改变时,调用事件,输出"change me".
JTool.php在protected/components 下
<?php
class JTool extends CComponent{
private $_width;
public function getWidth(){
return $this->_width ? $this->_width : 1;
}
public function setWidth($width){
if($this->hasEventHandler('onChange')){
$this->onChange(new CEvent());
}
$this->_width = $width;
}
public function onChange($event){
$this->raiseEvent('onChange', $event);
}
}
OK,功能已经实现了,找个控制器,执行
$j = new JTool();
$j->onChange = "showChange"; //给事件绑定handle showChange
$j->width = 100; //调用setWidth,解发绑定的事件showChange
function showChange(){
echo 'changed me';
}
现在我们想给JTool添加一个功能,返回长度的100倍,我们可以继承JTool.php写一个方法
class JToolSub extends JTool{
public function get100width(){
return $this->width*100;
}
}
OK,功能实现了,这个执行就简单了new JToolSub调用方法即可
上边的这两种办法,就是仅完成功能,下边演示Behavior及events来实现
如何用Behavior来实现上边的增加一个方法,返回长度的100倍的功能呢?
写类JBe
JBe.php在protected/behavior 下
class JBe extends CBehavior{
public function get100width(){
return $this->Owner->width*100;
}
}
OK,功能已经实现了,找个控制器,执行
$j = new JTool();
$j->attachBehavior('JBe', 'application.behavior.JBe');
echo $j->get100width();
如何用Behavior实现JTool中的长度改变时,调用一个事件的功能呢?
写类JBe
class JBe extends CBehavior{
public function events(){
return array_merge(parent::events(),array(
'onChange'=>'change',
));
}
public function change(){
echo 'changed';
}
public function get100width(){
return $this->Owner->width*100;
}
}
OK,功能实现随便找个控制器,执行
$j = new JTool();
$j->attachBehavior('JBe', 'application.behavior.JBe');
$j->width = 100;
这里的要点是events方法
返回的数组array('onChange'=>'change')定义了事件(event)和对应的事件处理方法(event hander)
事件是是Compents(JTool中)定义的,即JTool中的onChange
处理方法同由Behavior(JBe中)类定义的,即JBe中的change
这样子再看CActiveRecordBehavior,其是绑定给CActiveRecord 这个组件的,绑定方法重写behaviors()
CActiveRecordBehavior中的events() 方法返回事件及事处理函数的对应,如:
'onBeforeSave'=>'beforeSave'
即组件CActiveRecord中的onBeforeSave这个事件对应的处理函数是
CActiveRecordBehavior中的beforeSave方法
这样子CActiveRecord在调用save()时,触发事件onBeforeSave,调用CActiveRecordBehavior对应的处理函数beforeSave
我们只要写一个CActiveRecordBehavior的子类,重写其中的beforeSave,执行一些操作,然后给CActiveRecord绑定即可
如果你自己有个目录下有些类或文件常用,可以在main.php的最上边定义一个路径别名
Yii::setPathOfAlias('local','path/to/local-folder');
如果是多个可以在main.php中的array中加一个配置
'aliases'=>array(
'local'=>'path/to/local/'
),
如何得到proteced目录的物理路径?
YII::app()->basePath;
widget是发布资源
$url = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('application.components.homeuserlived'));
cs()->registerCoreScript('jquery');
cs()->registerScriptFile($url.'/location.js' ,CClientScript:OS_HEAD);
cs()->registerScriptFile($url.'/YLChinaArea.js' ,CClientScript:OS_HEAD);
cs()->registerCssFile($url.'/style.css');
如何写application component, 即在main.php可配置
"my"=>array('')
可以通过Yii::app()->my来访问?
继承CApplicationComponent即可,并可以自带Behavior等
yii中读写session的两种方法
$session = Yii::app()->session;
$session['terry'] = 30;
var_dump($session['key']);
Yii::app()->user->setState('tom', '40');
var_dump(Yii::app()->user->getState('key', 'default'));
==========================================分隔线===================================
soap非yii教程,意思是不用yii框架的时候要对象提供webservice的写法
分两种WSDL模式,和非WSDL模式,先看后者
这个也比较简单,服务器端
server.php
<?php
ini_set('soap.wsdl_cache_enabled',0);
class Student {
public function getInfo($name,$age){
if($age == 20){
throw new SoapFault(-1, 'Cannot divide by zero!');
}
$xml = "<root><name>".$name."</name>";
$xml .= "<age>".$age."</age></root>";
return $xml;
}
}
$soapS = new SoapServer(null,array('uri' => 'http://www.dayouhui.com'));
$soapS->setClass('Student');
$soapS->handle();
?>
客户端client.php
<?php
$soap = new SoapClient(null,array('location'=>"http://localhost/mysoap/index.php",'uri'=>'inadex.php'));
echo $soap->getInfo('a','b');
这样子即可
=============================================
yii,Componnts那快,忘了,写了个小例子回忆了下
是写一个可以写在main.php中的Components并绑定行为,事件
======================================
class ExtWindow extends CApplicationComponent{
private $title = 'title';
public $oldtitle;
public function getTitle(){
return $this->title ? $this->title : 'old title<br />';
}
public function setTitle($title){
echo '=='.$this->oldtitle.'==';
$this->oldtitle = $this->title;
$this->title = $title;
if($this->hasEventHandler('onTitleChange')){
$event =new CEvent($this);
$this->raiseEvent('onTitleChange', $event);
}
}
//必须有这么个方法,其和raiseEent中的事件一样,具体看代码
public function onTitleChange($event){
}
}
===========================
<?php
class Window extends CBehavior{
public function events(){
return array_merge(parent::events(),array(
'onTitleChange'=>'titleChange',
));
}
public function titleChange($event){
echo $event->sender->title;
echo 'event TitleChange is handled in Behavior<br />';
echo $this->owner->title;
}
public function titleOld(){
echo '<br />old title is is '.$this->owner->oldtitle;
}
}
==============================
main.php中的写法
'ExtWin'=>array(
'class' => 'ExtWindow',
'oldtitle'=>'我是旧的',
'behaviors'=>array('win'=>'application..behavior.Window')
=============================================
一对多,多对多的关联时最后的参数 together说明
如果为false,分开查多个语句
如果为true,强制生成一个语句
如果没有设置,分页页生成多个语句,不分页时生成一个语句
),
多对多时,查询时,中间表的名子叫 (关联名_关联名)
with选项的作用是eager loading
together的作用是 要不要形成一个语句
当是一个sql语句是记录会有重复,这时候分页分出现相同的记录,加上group=>true即可,
只要弄明白了,你生成的sql是一条还是多条sql就明白在多对多查询时的结果了
两个表不是用主键关联
'user' => array(self::BELONGS_TO, 'OaskUser', '','on'=>'name=userName', 'select'=>'TrueName'),

论坛徽章:
0
2 [报告]
发表于 2012-01-10 15:47 |只看该作者
谢谢分享
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP