記事の表示
このブログシステムは、記事を一覧と個別での表示が出来る。
一覧は”index”操作として実装され、個別記事は”view”操作として実装される。
view操作のカスタマイズ
“view”を操作しているPostControllerファイルの『actionView()』と『loadModel()』を編集する。
/**
*
* ビューアクション
*
**/
public function actionView()
{
// 記事読み込み
$post = $this->loadModel();
// 個別表示ページにレンダリング
$this->render(
'view',
array('model'=>$post)
);
}
private $_model;
/**
*
* 記事読み込み
*
**/
public function loadModel()
{
/**
*
* 記事読み込み
*
**/
public function loadModel()
{
if($this->_model === null)
{
if(isset($_GET['id']))
{
if(Yii::app()->user->isGuest)
{
// ゲストユーザ:公開記事とアーカイブは許可
$condition = 'status='.Post::STATUS_PUBLISHED.' OR status='.Post::STATUS_ARCHIVED;
}
else
{
// ゲストユーザ以外は全て許可
$condition = '';
}
// 記事データ取得
$this->_model = Post::model()->findByPk($_GET['id'], $condition);
}
// 記事情報がない場合は404ページへ遷移する
if($this->_model === null)
{
throw new CHttpException(404, 'リクエストされたページは存在しません。');
}
}
return $this->_model;
}
index操作のカスタマイズ
“view”ファイル同様にPostControllerファイルの『actionIndex()』を編集する
/**
*
* インデックスアクション
*
**/
public function actionIndex()
{
$criteria = new CDbCriteria(
array(
// 公開済みの記事
'condition'=>'status='.Post::STATUS_PUBLISHED,
// 更新時間順
'order'=>'update_time DESC',
// 記事のコメント数
'with'=>'commentCount',
)
);
if(isset($_GET['tag']))
{
// 特定のタグ指定があれば絞り込み条件を追加する
$criteria->addSearchCondition('tags', $_GET['tag']);
}
// データプロバイダーを生成
$dataProvider = new CActiveDataProvider(
'Post',
array(
'pagination'=>array(
// 1頁あたり5記事を表示する
'pageSize'=>5,
),
'criteria'=>$criteria,
)
);
// 一覧情報をレンダリングする
$this->render(
'index',
array('dataProvider'=>$dataProvider)
);
}
続いてビューファイルの”index”を編集する
<?php if(!empty($_GET['tag'])): ?>
<h1>Posts Tagged with <i><?php echo CHtml::encode($_GET['tag']); ?></i></h1>
<?php endif; ?>
<?php
$this->widget(
'zii.widgets.CListView',
array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'template'=>"{items}\n{pager}",
)
);
?>
"CListView"ウィジェットは、個々の記事の詳細を表示するために部分的ビュー(partial view)を必要とする。 ここで"partial view"として指定している"_view"は"/blog/protected/views/post/_view.php"である。 このビュースクリプトの中では"$data"というローカル変数を使って、記事のインスタンスにアクセス出来る。
参考サイト:
http://www.yiiframework.com/doc/blog/1.1/ja/post.display



