石头杨 2016-08-19 20:27:09 13562次浏览 9条评论 13 8 0

学习 YII 以来,一直在yiichina中潜水,查找资料、观看文章,受益众多。对 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提示成功就行了。

b17b1193-9f53-4fab-aba6-21b82c8275c6.png

此时,打开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。

e541df85-2289-44b2-b94f-a6a948f61ee1.png

详细的填写信息如图中所示,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_atupdate_at ,修改一条数据时自动更新update_at。设置行为后,必须去掉 验证规则里关于created_atupdate_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.按如下填写然后生成。

da5b9fd1-1712-4acd-82e7-f10beedf15b2.png

生成后,进入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表的结合。更新时间待定。

觉得很赞
  • 评论于 2017-07-18 13:10 举报

    看不懂....刚开始学

  • 评论于 2016-12-11 10:19 举报

    要是配合详解一下源码就有意思了,感谢分享,已经路转粉了

  • 评论于 2016-11-28 22:41 举报

    做完了吗

  • 评论于 2016-10-14 16:07 举报

    赞一个,这个过程比很多有头无尾的要强,而且每一步都有说明!

  • 评论于 2016-09-08 13:10 举报

    赞一个,这个过程比很多有头无尾的要强,而且每一步都有说明!

  • 评论于 2016-09-02 10:00 举报

    修改index.php的GridView部件如下 这个index.php backend里的?还是是哪里的 怎么没有您说的 GridView部件
    打开GII 选择cru Generator.按如下填写然后生成。这里你填的是 frontend 的下面路径。。。

    1 条回复
    评论于 2016-09-02 10:13 回复

    我自己把你第二张图片上的 viewpach路径改成 backend的了。呵呵 其他的代码都能用,但是 post 要改成posts 。。。才行,这个教程挺好的。。。亲测 前后台 都能 进去了,谢谢作者。继续写下去,尽量,谢谢,

    觉得很赞
  • 评论于 2016-08-30 09:48 举报

    在请教一下 post在后台的增删改查这一步视图文件怎么会是放在frontend下呢 不知应该放在backend下的view中

    1 条回复
    评论于 2016-09-02 11:45 回复

    不好意思,创建增删改查那张图确实有问题,viewpath的路径应该为 @backend/views/posts。

  • 评论于 2016-08-29 14:36 举报

    想跟你请教一下你是怎么自学的,自学的时候有些地方就看不懂,比如你文章的$this->params['breadcrumbs'][]面包屑导航我就是不知道他其中的原理,只是想了解怎么使用它,不用了解太深。

    2 条回复
    评论于 2016-08-29 15:53 回复

    一是上网百度,一般都能搜到一些。
    二是上网下一些 Yii 的开源项目,看别人是怎么用的,自己照着写一遍,就能懂个大概了。
    三是看源码,找到该部件的源码,看看注释、属性、方法。都能发现有用的东西。

    评论于 2016-08-30 08:36 回复

    谢谢啦 我也是自学 希望快点进步

    觉得很赞
  • 评论于 2016-08-27 11:52 举报

    tu pian xiao le kan bu qing

    1 条回复
    评论于 2016-08-27 11:58 回复

    点击会放大的,一般浏览器都有着功能吧

您需要登录后才可以评论。登录 | 立即注册