注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

老狗的博客

尽管每一步都很微小,但我确认我在进步

 
 
 

日志

 
 
关于我
sky

认真生活,努力工作 热爱技术,关注DB,存储,分布式,中间层,java,c++,php

网易考拉推荐

yii framework工作流2-【提交数据校验/抽取/db操作/model属性访问】  

2013-07-05 18:08:39|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

1. 用户从页面提交数据或者动作,可以通过get进行显式提交,如下:

http://127.0.0.1/blog/index.php?r=post/view&id=6


则?号之后的部分即为get的参数(r=post/view&id=6)


对于get方法的扑捉,yii framework提供了action parameter binding的方式进行捕捉

pubic function actionView($id);

这样,在actionView函数中就已经拿到$_Get中对应的action参数的值了,

protected function runWithParamsInternal($object, $method, $params)
{
$ps=array();

//本质就在这个地方,在这个地方,对于参数进行了板顶
foreach($method->getParameters() as $i=>$param)
{
$name=$param->getName();
if(isset($params[$name]))
{
if($param->isArray())
$ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
elseif(!is_array($params[$name]))
$ps[]=$params[$name];
else
return false;
}
elseif($param->isDefaultValueAvailable())
$ps[]=$param->getDefaultValue();
else
return false;
}
$method->invokeArgs($object,$ps);
return true;
}

2. 用户也可以通过post方式进行隐式提交,如下:

用户创建一个post,通过

http://127.0.0.1/blog/index.php?r=post/view提交


对于Post方法的提交,yii通过massive assignment提取数据

$model=new Post;
if(isset($_POST['Post']))
{

//这个就是massive assisgnment,可以将定义的所有safe attribute的值从$_POST['Post']中提取出来
$model->attributes=$_POST['Post'];
}

safe attribute的意思是将一些不安全的属性从massive assisgmment中去除掉,定义如下:

return array(

//required,可以认为title, content, status是safe的
array('title, content, status', 'required'),
array('title', 'length', 'max'=>128),
array('status', 'in', 'range'=>array(1,2,3)),
array('tags', 'match', 'pattern'=>'/^[\w\s,]+$/', 'message'=>'tags can only contain word characters'),
array('tags', 'normalizeTags'),

//同时tags也是safe的
array('tags', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.

//title, status,在actionSearch的时候也是安全的
array('title, status', 'safe', 'on'=>'search'),
);


2. 数据校验,当用户提交的表单数据抽取完毕之后,model的属性都得到了填充

CModel:

public function validate($attributes=null, $clearErrors=true)
{
if($clearErrors)
$this->clearErrors();
if($this->beforeValidate())
{
foreach($this->getValidators() as $validator)
$validator->validate($this,$attributes);
$this->afterValidate();
return !$this->hasErrors();
}
else
return false;
}

CValidator:

public function validate($object,$attributes=null)
{
if(is_array($attributes))
$attributes=array_intersect($this->attributes,$attributes);
else
$attributes=$this->attributes;
foreach($attributes as $attribute)
{
if(!$this->skipOnError || !$object->hasErrors($attribute))
$this->validateAttribute($object,$attribute);
}
}


关于model的场景scenario的问题

CModel:

private $_scenario=''; // scenario

CFormModel:
public function __construct($scenario='')
{
$this->setScenario($scenario);
$this->init();
$this->attachBehaviors($this->behaviors());
$this->afterConstruct();
}

CActiveRecord:
public function __construct($scenario='insert')
{
if($scenario===null) // internally used by populateRecord() and model()
return;

$this->setScenario($scenario);
$this->setIsNewRecord(true);
$this->_attributes=$this->getMetaData()->attributeDefaults;

$this->init();

$this->attachBehaviors($this->behaviors());
$this->afterConstruct();
}


3. db操作

db操作主要用到CActiveRecord类,CDbCriteria类,CPagenation类,以及CActiveDataProvider类

CActiveRecord extends CModel


CDbCriterai extends CComponent

//最终结果要包含哪些列

public $select='*';
/**
* @var boolean whether to select distinct rows of data only. If this is set true,
* the SELECT clause would be changed to SELECT DISTINCT.

*结果是否要唯一
*/
public $distinct=false;
/**
* @var string query condition. This refers to the WHERE clause in an SQL statement.
* For example, <code>age>31 AND team=1</code>.

*条件可以通过add方法或者compare等进行拼凑
*/

public $condition='';
/**
* @var array list of query parameter values indexed by parameter placeholders.
* For example, <code>array(':name'=>'Dan', ':age'=>31)</code>.
* 查询参数值数组,通过参数的占位符进行索引
*/
public $params=array();
/**
* @var integer maximum number of records to be returned. If less than 0, it means no limit.

*用于分组
*/
public $limit=-1;
/**
* @var integer zero-based offset from where the records are to be returned. If less than 0, it means starting from the beginning.
*/
public $offset=-1;
/**
* @var string how to sort the query results. This refers to the ORDER BY clause in an SQL statement.

*用于排序
*/
public $order='';
/**
* @var string how to group the query results. This refers to the GROUP BY clause in an SQL statement.
* For example, <code>'projectID, teamID'</code>.
*/
public $group='';
/**
* @var string how to join with other tables. This refers to the JOIN clause in an SQL statement.
* For example, <code>'LEFT JOIN users ON users.id=authorID'</code>.
*/
public $join='';
/**
* @var string the condition to be applied with GROUP-BY clause.
* For example, <code>'SUM(revenue)<50000'</code>.
*/
public $having='';
/**
* @var mixed the relational query criteria. This is used for fetching related objects in eager loading fashion.
* This property is effective only when the criteria is passed as a parameter to the following methods of CActiveRecord:
* <ul>
* <li>{@link CActiveRecord::find()}</li>
* <li>{@link CActiveRecord::findAll()}</li>
* <li>{@link CActiveRecord::findByPk()}</li>
* <li>{@link CActiveRecord::findAllByPk()}</li>
* <li>{@link CActiveRecord::findByAttributes()}</li>
* <li>{@link CActiveRecord::findAllByAttributes()}</li>
* <li>{@link CActiveRecord::count()}</li>
* </ul>
* The property value will be used as the parameter to the {@link CActiveRecord::with()} method
* to perform the eager loading. Please refer to {@link CActiveRecord::with()} on how to specify this parameter.
* @since 1.1.0
*/
public $with;
/**
* @var string the alias name of the table. If not set, it means the alias is 't'.
*/
public $alias;
/**
* @var boolean whether the foreign tables should be joined with the primary table in a single SQL.
* This property is only used in relational AR queries for HAS_MANY and MANY_MANY relations.
*
* When this property is set true, only a single SQL will be executed for a relational AR query,
* even if the primary table is limited and the relationship between a foreign table and the primary
* table is many-to-one.
*
* When this property is set false, a SQL statement will be executed for each HAS_MANY relation.
*
* When this property is not set, if the primary table is limited or paginated,
* a SQL statement will be executed for each HAS_MANY relation.
* Otherwise, a single SQL statement will be executed for all.
*
* @since 1.1.4
*/
public $together;


关联

AR 中定义关系需要覆盖 CActiveRecord 中的 relations() 方法。此方法返回一个关系配置数组。每个数组元素通过如下格式表示一个单一的关系

'VarName'=>array('RelationType', 'ClassName', 'ForeignKey', ...additional options)

http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.arr



4. model属性存取

对于继承了CActiveRecord的model类来说,会多出很多的虚属性:

class Post extends CActiveRecord;

这个类并没有定义title,content此类属性,但是我们却可以使用$model->content来引用?系统如何实现?

CActiveRecord类重新定了了_get方法,所以相关的一系列成为了虚属性(Magic Property)

**
* PHP getter magic method.
* This method is overridden so that AR attributes can be accessed like properties.
* @param string $name property name
* @return mixed property value
* @see getAttribute
*/
public function __get($name)
{

//这一段代码检查了数组中是否有以$name索引的这个属性,如果有,则返回数组中以$name索引的数据
if(isset($this->_attributes[$name]))
return $this->_attributes[$name];

elseif(isset($this->getMetaData()->columns[$name]))
return null;

//这一段代码调用了reations中定义的关系
elseif(isset($this->_related[$name]))
return $this->_related[$name];
elseif(isset($this->getMetaData()->relations[$name]))
return $this->getRelated($name);
else
return parent::__get($name);
}


  评论这张
 
阅读(523)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018