yii2博客学习笔记(一)

技巧库 · stoneyang · 于 7年前 发布 · 7614 次阅读

学习 YII 以来,查找资料、观看文章,受益众多。对 YII 自我感觉基本入门,于是决定做个博客检验自己的学习成果。本系列纯属个人学习笔记文章,诸多不足,多多谅解,大神轻喷。如能稍加指点,则感激不敬。

开发目标:

基于MarkDown的个人博客开发。

开发环境:

  • PHP 版本为 5.5.9;
  • YII 2.0.9 advanced版本;
  • YII扩展,yidashi/yii2-bootstrap-markdown,安装方法 composer require "yidashi/yii2-bootstrap-markdown";

文章表的前后台开发

万事具备,开始开发啦!!! Yii 如何安装,怎么设置数据库信息就不累述了,出门左转百度。

第一步 posts 表的建立。

项目根目录打开命令行,也就是advanced目录,输入 .\yii migrate/create posts,出现提示信息在输入y提示成功就行了。

此时,打开console\migratinos文件夹。你就能看到 m160819_081946_posts.php 这个文件了。文件已经静静的躺在里面啦! 然后将文件编辑内容编辑为如下这样。当然,可以自己添加修改字段。

<?php
use yii\db\Migration;
class m160817_071301_post extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }
        $this->createTable('{{%posts}}', [
            'id' => $this->primaryKey(),
            'title' => $this->string()->notNull(),
            'author' => $this->string()->notNull(),
            'content'=> $this->text(),
            'status' => $this->integer(1)->notNull()->defaultValue(1),
            'created_at' => $this->integer()->notNull(),
            'updated_at' => $this->integer()->notNull(),
        ], $tableOptions);
    }
    public function down()
    {
        echo "m160817_071301_blog cannot be reverted.\n";
        return false;
    }
    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }
    public function safeDown()
    {
    }
    */
}

各字段的含义相信大家都能看懂,接着打开命令行,输入输入 .\yii migrate,出现提示信息在输入y提示成功就行了。此时打开数据库,posts表已经静静的躺在里面啦!

posts 前台显示开发

接下来,做前台 post 的列表显示和详细页。Yii 提高生产率的 Gii 工具登场了。在浏览器进入 Gii 界面,选择 Model Generator。

详细的填写信息如图中所示,Namespace 之所以选择 common\models ,是因为前后台都要用到。之后在 common\models 文件夹下发现 post 文件就ok了。 然后修改post文件如下

<?php
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
 * This is the model class for table "posts".
 *
 * @property integer $id
 * @property string $title
 * @property string $author
 * @property string $content
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
class Posts extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    const STATUS_ACTIVE = 1;
    public static function tableName()
    {
        return 'posts';
    }
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'author'], 'required'],
            [['content'], 'string'],
            [['status'], 'integer'],
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            [['title', 'author'], 'string', 'max' => 255],
        ];
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'author' => '作者',
            'content' => '内容',
            'status' => '状态',
            'created_at' => '编写时间',
            'updated_at' => '更新时间',
        ];
    }
}

这里我们添加了 TimestampBehavior 行为,这个行为的作用是在新建一条数据时,自动插入created_at 和 update_at ,修改一条数据时自动更新update_at。设置行为后,必须去掉 验证规则里关于created_at 和 update_at 的验证,不然会冲突。其他修改,大家应该都能看懂。 接着在选择 Controller Generator。Controller Class 填写 frontend\controllers\PostController 。 View Path 填写 @frontend/views/post。生成控制器文件。 接着打开 frontend\controllers\PostController.php 文件,修改内容如下:

<?php
namespace frontend\controllers;
use common\models\Posts;
use yii\data\Pagination;
class PostController extends \yii\web\Controller
{

    public function actionSeeder()
    {
        $faker = \Faker\Factory::create('zh_CN');
        $a=0;
        for ($i=0; $i <20 ; $i++) {
            $posts = new Posts();
            $posts->title = $faker->text($maxNbChars = 20);
            $posts->author = $faker->name;
            $posts->content = $faker->text($maxNbChars = 3000);
            if ($posts->insert()) {
                 $a+=1;
            }else{
            }
        }
        echo "添加".$a."条数据";
    }

    public function actionIndex()
    {
    	$posts = Posts::find()->where(['status' => 1])->orderBy(['id'=>SORT_DESC]);
    	$countuPosts = clone $posts ;
        $pages = new Pagination(['totalCount' => $countuPosts->count(),'pageSize'=>5]);
        $models = $posts->offset($pages->offset)
        ->limit($pages->limit)
        ->all();
       return $this->render('index', [
         'models' => $models,
         'pages' => $pages,
       ]);
    }

    public function actionItem($id )
    {
    	$post = Posts::findOne($id);
        return $this->render('item',['post'=>$post]);
    }
}

控制器里有三个方法,actionSeeder方法 是向数据库posts表添加假数据的,\Faker\Factory 包是 Yii 自带的,用来生成随机数据的,详细用法百度得之。actionIndex方法没什么好说的,分页显示Posts 表的数据,yii手册详细有些。 actionItem 则是显示每个文章的详情页。

然后进入 frontend\views\post文件夹,修改index.php文件如下。

<?php
/* @var $this yii\web\View */
use yii\widgets\LinkPager;
use yii\helpers\Url;
$this->title = '博客首页-不吃鱼的猫';
$this->params['breadcrumbs'][] = $this->title;
?>
<h1>不吃鱼的猫</h1>
<div class="panel panel-default">
  <div class="panel-heading">博客</div>
  <div class="panel-body">
<?php
foreach ($models as $model) {
?>
  <div class="media">
   <!-- <div class="media-left">
    <a href="#">
      <img class="media-object" src="..." alt="...">
    </a>
    </div> -->
   <div class="media-body">
    <h4 class="media-heading"><a href="<?php echo Url::toRoute(['post/item', 'id' => $model->id]); ?>"><?php echo $model->title; ?></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<small>作者:<?php echo $model->author; ?></small></h4>
    <p><?php echo substr($model->content,0,250)."......"; ?></p>
  </div>
</div>
<?php
}
echo LinkPager::widget(['pagination' => $pages,]);
?>
 </div>
</div>

在frontend\views\post 下,新建item.php,内容如下。

<?php
/* @var $this yii\web\View */
$this->title = $post->title;
$this->params['breadcrumbs'][] = ['label' => 'Posts', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<h1><?php echo  $post->title; ?></h1>
<p class="text-muted">作者:<?php echo $post->author; ?></p>
<p>
    <?php echo yii\helpers\Markdown::process($post->content, 'gfm'); ?>
</p>

接着进入frontend\views\layouts文件夹中,在main.php布局文件中添加 $menuItems 中

$menuItems = [
        ['label' => '博客', 'url' => ['/post/index']],
        ['label' => 'Home', 'url' => ['/site/index']],
        ['label' => 'About', 'url' => ['/site/about']],
        ['label' => 'Contact', 'url' => ['/site/contact']],
    ];

post 后台搭建。

打开GII 选择cru Generator.按如下填写然后生成。

生成后,进入backend\views\post,找到_form.php文件,修改如下

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\models\Posts */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="posts-form">
    <?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'author')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'content')->widget('yidashi\markdown\Markdown',['language' => 'zh']); ?>

    <?= $form->field($model, 'status')->textInput() ?>
    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>
    <?php ActiveForm::end(); ?>
</div>

然后view.php文件中的DetailView 小部件修改如下

<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        'id',
        'title',
        'author',
        'content:ntext',
        'status',
        'created_at:datetime',
        'updated_at:datetime',
    ],
]) ?>

修改index.php的GridView部件如下。

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn',
          'header'=>'id'],
        //'id',
        'title',
        'author',
       // 'content:ntext',
        //'status',
        [
           'attribute' => 'status',
           'value'=>function ($model,$key,$index,$column){
                  return $model->status==1?'正常':'已删除';
            },
            //在搜索条件(过滤条件)中使用下拉框来搜索
            'filter' => ['1'=>'正常','0'=>'已删除'],
            //or
            'filter' => Html::activeDropDownList($searchModel,
                        'status',['1'=>'正常','0'=>'已删除'],
                        ['prompt'=>'全部']
             )
        ],
        // 'created_at',
        // 'updated_at',
        ['class' => 'yii\grid\ActionColumn',
        'header' => '操作',
       ],
    ],
]); ?>

接着进入backend\views\layouts文件夹中,在main.php布局文件中添加 $menuItems 中

$menuItems = [
    ['label' => 'Home', 'url' => ['/site/index']],
    ['label' => '文章', 'url' => ['/post/index']],
];

总结

至此,posts表的前后台就搭建完成了。大家多多提提意见吧。下一章要写的是tag标签的搭建和posts表的结合。更新时间待定。

本文由 stoneyang 创作,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。

本帖已被设为精华帖!
共收到 3 条回复
ppker#17年前 0 个赞

very nice 一起学习

lzhui#27年前 0 个赞

感觉写的还是比较亲民化的,通俗易懂,不错。

getadmin#36年前 0 个赞

挺好的

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册