yii2框架学习笔记三

https://github.com/yiisoft/yii2/releases/download/2.0.22/yii-advanced-app-2.0.22.tgz

https://github.com/yiisoft/yii2/archive/2.0.22.zip
https://www.yiichina.com/video
https://www.yii-china.com/post/detail/15.html

https://www.yii-china.com/post/detail/3.html

yii2-file-upload.zip



1.场景应用
2.通过表单模型实现业务逻辑


const SCENATIOS_CREATE='create';
const SCENARIOS_UPDATE='update';
const IS_VALID=1;

public function rules(){
	return [
		[],
		[],
		[]
	];
}

public function actionCreate(){
	$model=new PostForm();
	//定义场景
	$model->setScenario(PostForm::SCENARIOS_CREATE);
	if($model->load(Yii::$app->request->post()) && $model->validate()){
		if($model->create()){
			Yii::$app->session->setFlash('warning',$model->_lastError);
		}else{
			return $this->redirect(['post/view','id'=>$model->id]);		
		}
	}
}

public function scenarios(){
	$scenarios=[
		self::SCENARIOS_CREATE=>['title','content','label_img','cat_id','tags'],
		self::SCENARIOS_UPDATE=>['title','content','label_img','cat_id','tags']
	];
	return array_merge(parent::scenarios(),$scenarios);
}

public function creat(){
	//事务
	$transaction=Yii::$app->db->beginTransaction();
	try{
		$model=PostModel();
		$model->setAttribute($this->attribute);
		$model->summary=$this->_getSummary();
		$model->user_id=Yii::$app->user->identiy->id;
		$model->user_name=Yii:$app->user->identity->identity->username;
		$model->create_at=time();
		$model->update_at=time();
		$model->is_valid=PostModel::IS_VALID;
		if($model->save){
			throw new \Exception('文章保存失败');
		}
		$this->id=$model->id;
		
		//调用事件
		$data=array_merge($this->getAttributes(),$model->getAttributes());
		$this->_eventAfterCreate($data);
		$transaction->commit();
		return true;
	}catch(\Exception $e){
		$transaction->rollBack();
		$this->_lastError=$e->getMessage();
		return false;
	}
}

public function _getSummary($s=0,$e=90,$char="utf-8"){
	if(empty($this->content))
		return null
	return (mb_substr(str_replace(' ','',strip_tags($this->content)),$s,$e,$char));
}

//文章创建之后事件
public function _eventAfterCreate($data){
	$this->on(self::Event_AFTER_CREATE,[$this,'_eventAddTag'],$data);
	$this->trigger(self::Event_AFTER_CREATE);
}



const Event_AFTER_CREATE="eventAfterCreate";
const Event_AFTER_UPDATE="eventAfterUpdate";

创建标签模型

class TagFrom extends Model{
	public $id;
	pubilc $tags;
	public function rules(){
		return [
			['tags','required'],
			['tags','each','rule'=>['string']]
		];
	}
}



//添加标签

public function _eventAddTag(){
	$tag=new TagFrom();
	$tag->tags=$event->data['tags'];
	$tagids=$tag->saveTags();
	
	//删除原先的关联关系
	RelationPostTagModel::deleteAll(['post_id'=>$event->data['id']]);
	//批量保存数据 文章和标签的关联关系
	if(!empty($tagids)){
		foreach($tagids as $k=>$id){
			$row[$k]['post_id']=$this->id;
			$row[$k]['tag_id']=$id;
		}
		$res=(new Query())->createCommand()
		->batchInsert(RelationPostTagModel::tableName(),['post_id','tag_id',$row])
		->execute();
		
		if(!$res){
			throw new \Exception('关联关系保存失败');
		}
	}
}


gii 命令

table name  relation_post_tags=> relation_post_tags;
model class => RelationPostTagModel


class TagFrom extends Model{
	public $id;
	public $tags;
	
	public function rules(){
		return[
			['tags','required'],
			['tags','each','rule'=>'string']
		];
	}
}




public function eventAddTag($event){
	$tag=new TagFrom();
	$tag->tags=$event->data['tags'];
	$tagids=$tag->saveTags();
	//删除原先的关联关系
	RelationPostTagModel::deleteAll(['post_id'=>$event->data['id']]);
	//批量保存数据
	
	if(!empty($tagids)){
		foreach($tagids as $k=>$v){
			$row[$k]['post_id']=$this->id;
			$row[$k]['tag_id']=$id;
		}
		$res=(new Query())->createCommand()
		->batchInsert(RelationPostTagModel::tableName(),['post_id','tag_id',$])
		->execute();
		
		if(!res){
			throw new \Exception('保存失败');
		}
	}
}




public function saveTags(){
	$ids=[];
	if(!empty($this->tags)){
		foreach($this->tags as $tag){
			$ids[]=$this->_saveTag();
		}
	}
	return $ids;
}


//gii 生成数据模型 tagModel


private function _saveTag(){
	$model=new TagModel();
	$res=$model->find()->where(['tag_name'=>$tag])->one();
	if(!$res){
		$model->tag_name=$tag;
		$model->post_num=1;
		
		if(!model->save()){
			throw new \Exception('保存标签失败');
		}else{
			$res->updateCounters(['post_num'=>1]);
		}
	}
	return $ids;
}




//关联模型

public function getViewById(){
	$res=PostModel::find()->with('relation.tag')->where(['id'=>$id])->asArray()->one();
	
	if(!$res){
		throw new NotFoundHttpException('找不到对应的页面');
	}
}




public function getRelate(){
	return $this->hasMany(RelationPostTagModel::className,['post_id'=>'id']);
}

class RelationPostTagModel extends Model



文章列表小组件


class PostWidget extends Widget{
	public $limit=6;
	public $more=true;
	public $page=false;
	
	public function run(){
		$curPage=Yii::$app->request->get('page',1);
		$cond=['=','is valid',PostModel::IS_VALID];
		$res=PostForm::getList($cond,$curPage,$this->limit);
		$result['title']=$this->title? :"最新文章";
		$result['more']=Url::to(['post/index']);
		$result['body']=$res['data']?:[];
		
		//是否显示分页
		if($this->page){
			$pages=new Pagination(['totalCount'=>$res['count'],'pageSize'=>$res['pageSize']]);
			$result['page']=$pages;
		}
		return $this->render('index');
	}
}




//文章表单模型定义方法 getList($cound,$curPage=1,$pageSize=5,$orderBy=['id'=>SORT_DESC])


public function getList($cound,$curPage=1,$pageSize=5,$orderBy=['id'=>SORT_DESC]){
	$model=new PostModel();
	$select=['id','title','summary','label_img','cat_id','user_id','user_name','is_valid','create_at','update_at'];
	
	$query=$model->find()->select($select)->where($cond)->with('relate.tag','extend')->orderBy($orderBy);
	
	//获取分页数据
	
	$res=$model->getPages($query,$curPage,$pageSize);
	
	//格式化数据
	$res['data']=self::_formatlist($res['data']);
	
	return $res;
}

public function _formatlist($data){
	foreach($data as &$list){
		$list['tag']=[];
		if(isset($list['relate']) && !empty($list['relate'])){
			foreach($list['relate'] as $lt){
				$list['tags'][]=$lt['tag']['tag_name'];
			}
		}
		unset($list['relate']);
	}
	return $data;
}

class BaseModel extends ActiveRecord{
	public function getPages($query,$curPage=1,$pageSize=10,$search=null){
		if($search){
			$query=$query->andFilerWhere($search);
			$data['count']=$query->count();
			
			if(!$data['count']){
				return ['count'=>0,'curPage'=>$curPage,'pageSize'=>$pageSize,'start'=>0,'end'=>0,'data'=>[]];
			}			
		}
		//超过实际页数,不取curPage为当前页
		$curPage=(ceil($data['count']/$pageSize)<$curPage)? ceil($data['count']/$pageSize):$curPage;
		
		//当前页
		$data['curPage']=$curPage;
		//每页显示条数
		$data['pageSize']=$pageSize;
		$data['start']=($curPage-1)*$pageSize+1;
		$data['end']=(ceil($data['count']/$pageSize)==$curPage)?$data['count']:($curPage-1)*$pageSize+$pageSize;
		
		//数据
		$data['data']=$query->offset(($curPage-1)*$pageSize)->limit($pageSize)->asArray()->all();
		
		return $data;
	}
}





轮播组建

class BannerWidget extends Widget{
	public $item=[];
	public function init(){
		if(empty($this->item)){
			$this->item=[
			['label'=>'demo','image_url'=>'/statics/images/banner/b_0.jpg','url'=>['site/index'],'html'=>'','active'=>'active'],
			['label'=>'demo','image_url'=>'/statics/images/banner/b_1.jpg','url'=>['site/index'],'html'=>'','active'=>'active'],
			['label'=>'demo','image_url'=>'/statics/images/banner/b_2.jpg','url'=>['site/index'],'html'=>'','active'=>'active'],
		];
		}
	}
	public function run(){
		$data['item']=$this->item;
		
		return $this->render('index',['data'=>$data]);
	}
}









//留言板

class FeedFrom extends Model{
	public $content;
	public $_lastError;
	public function rules(){
		return [
			['content','require'],
			['content','string','max'=>255]
		];
	}
	public function attributeLabels(){
		return [
			'id'=>'ID',
			'content'=>'内容'
		];
	}
}





//留言板小组件

---|chat
------|views
---|Chatwidget.php


class Chatwidget extends Widget{
	public function run(){
		$feed=new FeedForm();
		$data['feed']=$feed->getList();
		return $this->render('index',['data'=>$data]);
	}
	public function getList(){
		$model=new FeedModel();
		$model->find()->limit(10)->with('user')->orderBy(['id'=>SORT_DESC])->asArray()->all();
		return $res?:[];
	}
}


public function actionAddFeed(){
	$model=new FeedForm();
	$model->content=Yii::$app->request->post('content');
	if($model->validate()){
		if($model->create()){
			return json_encode(['status'=>true]);
		}
	}
	return json_decode(['status'=>false,'msg'=>'发布失败!']);
}




public function creat(){
	try{
		$model=new FeedModel();
		$model->user_id=\Yii::$app->$user->identity->id;
		$model->content=$this->content;
		$model->create_at=time();
		
		if(!$model->save())
			throw new \Exception('保存失败');
			
		return true;
	}catch(\Exception $e){
		$this->_lastError()=$e->getMessage();
		return false;
	}
}



//热门浏览组件

class HotWidget extends Widget{
	public $title='';
	public function run(){
		$res=(new Query())->select()->from(['a'=>PostExtendModel::tableName()])->join('left join',['b'=>PostModel::tableName()],['a.post_id=b.id'])
		->where('b.is_valid='.$PostModel::IS_VALID)
		->orderBy(['browser'=>SORT_DESC,'id'=>SORT_DESC])
		->limit($this->limit)
		->all();
		
		$result['title']=$this->title?:'热门浏览';
		$result['body']=$res?:[];
		
		return $this->render('index',['data'=>$result]);
	}
}



//标签云组件

class TagWidget extends Widget{
	public $title='';
	public $limit=20;
	public function run(){
		$res=TagModel::find()
		->orderBy(['post_num'=>SORT_DESC])
		->limit($this->limit)
		->all();
		
		$result['title']=$this->title?:'标签云';
		
		$result['body']=$res?:[];
		
		return $this->render('index',['data'=>$result]);
		
	}
}


//真实前端页面

<?php
user yii\helpers\Url;
?>

<div class="pannel-title box-title">
	<span><strong><?=$data['title']?></strong></span>
	<div class="pannel-body padding-left-0">
		<div class="tag-clount">
			<?php foreach($data['body'] as $list)?>
			<a href="<?=Url::to(['post/index','tag'=>$list['tag_name']])?>"><?=$list['tag_name']?></a>
			<?php endforeach;?>
		</div>
	</div>
</div>



<?=HotWidget::widget()?>
<?=Tagwidget::widget()?>








 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值