Yii 控制器模型的使用总结
kevin.Zhu 发布于:2017-5-29 11:06 分类:Php 有 15 人浏览,获得评论 0 条
<?php /** * 演示页面控制器 * User: zkf * Date: 17-5-28 * Time: 上午11:18 */ class SampleController extends Controller { function init() { //定义控制器自己的Layout, 不定义的话将使用main.php中定义的layout $this -> layout = '' ; } /** * 可以通过actions将action定义在外部文件中 * 这样的一个好处是不容易出现版本冲突 也方便对action做及时的版本切换 */ function actions() { return array( 'index' => array( 'class' => 'application.controllers.sample.IndexAction', ) , 'xxx' => array( 'class' => 'xxx', ), ) ; } /* * 常规的action定义 function actionIndex() { //不使用Layout进行渲染 $this -> renderPartial('index') ; $this -> render('index') ; } */ // 取表数据的例子 function actionSampletest() { //返回components中定义的Log数据库连接对象 //可以通过定义ActiveRecord模型时重写getDbConnection方法 返回$db2对象,用以修改模型的数据库为dbLog $db2 = Yii::app() -> dbLog ; //返回db2连接对象定义的属性 username $db2_user = Yii::app() -> dbLog ->username ; $m_user = User::model() ; $c = new CDbCriteria() ; //$c -> select = array('ID', 'Name') ; //$c -> select = 'ID, Name' ; $c -> condition = '' ; $c -> order = 'ID desc' ; //$c -> limit = 3 ; // //$c -> offset = 10 ; //偏移量 $total = $m_user -> count() ; $pg = new CPagination($total) ; $pg -> pageSize = 4 ; $pg -> applyLimit($c) ; //$lst = $m_user -> find() -> attributes ; //$lst = $m_user -> find('id=:id', array('id' => 8)) -> attributes ; $lst = $m_user -> findAll($c ) ; //$lst = CHtml::listData($lst, 'ID', 'Name') ; } /** * 常规的AR用法 , 不好用 功能太弱 用起来也不方便 */ function actionSample0() { //$m_user = new User() ; $m_user = User::model() ; //$data = $m_user -> findByAttributes( array('ID' => 1) ) ; $data = $m_user -> find ( 'ID=1' ) ; $data = $m_user -> findByPk (1) ; $data = $m_user -> count ("RoleID=1") ; $data = $m_user -> findAllByAttributes( array('RoleID' => 2) ) ; //$data = $m_user -> findAllBySql( "select * from User where RoleID=2" ) ; $data = $this -> _arLst2Arr($data) ; } /** * 使用封装好的CDBCriteria操作方法 来取列表数据 */ function actionSample2 () { $m_user = User::model() ; $c = $this -> _arGet('', 'ID desc') ; $lst = $m_user -> findAll($c) ; $lst = $this -> _arLst2Arr($lst) ; } /** * 封装了对cdbcriteria对象的设置 * * @param $where * @param $order * @param string $field * @param int $start * @param int $limit * @return CDbCriteria */ function _arGet($where='', $order='', $field= '', $start = 0, $limit = 0) { $c = new CDbCriteria ; if($where) { $c->condition = $where; } if($order) { $c->order = $order; } if($start > 0 ) { $c->offset = $start; } if($limit > 0 ) { $c->limit = $limit; } if(strlen($field) ) { $c->select = $field; } return $c ; } /** * 将通过cdbcriteria返回的对象列表转成数组列表 * @param $cdbcRtnLst * @return array */ function _arLst2Arr ($cdbcRtnLst) { $rtn = array() ; foreach ($cdbcRtnLst as $item) { array_push($rtn, $item -> attributes ) ; } return $rtn ; } }