用Yii基础版快速搭建可运行的个人博客需避开Composer缓存等陷阱:执行composer create-project不加--prefer-dist;配置数据库并运行迁移建post表;用Gii生成Post模型与CRUD;调整入口路径并设defaultRoute为post/index。

用Yii基础版快速搭建一个能跑起来的个人博客,不是只写个Hello World,而是要有文章列表、详情页、数据库表结构和后台管理入口——这需要从项目生成开始就避开Composer缓存陷阱、目录权限坑和路由配置雷区。
创建基础项目并避开压缩包陷阱
打开终端,进入你打算存放项目的目录(比如D:\www或/var/www/html),执行以下命令:
composer create-project yiisoft/yii2-app-basic blog
【不要加--prefer-dist参数】。这个参数会让Composer拉取预编译的tar包,而这些包在某些镜像源下存在损坏风险,导致vendor/autoload.php缺失或Gii无法加载——首次搭建必须让Composer clone完整git历史。
等待安装完成,你会看到blog/目录里包含config/、controllers/、models/、views/、web/等标准结构。
配置数据库与运行迁移
编辑config/db.php,填入你本地MySQL的实际连接信息:
'dsn' => 'mysql:host=localhost;dbname=blog_dev;charset=utf8mb4',
'username' => 'root',
'password' => '123456',
确保runtime/和web/assets/两个目录具备写权限:Windows下右键→属性→安全→给IIS用户或Apache服务账户“修改”权限;Linux/macOS执行:
chmod 777 runtime web/assets
接着在blog/目录下运行迁移命令:
php yii migrate/create create_posts_table
该命令会在migrations/目录生成一个类似m260806_111502_create_posts_table.php的文件。打开它,把up()方法改成:
public function up($this->createTable('post', [
'id' => $this->primaryKey(),
'title' => $this->string(200)->notNull(),
'content' => $this->text()->notNull(),
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
]);
再执行:
php yii migrate
此时数据库中已建好post表,字段含主键、标题、正文、创建和更新时间戳。
生成Post模型与CRUD界面
启动Web服务器,访问http://localhost/blog/web/index.php?r=gii(如提示密码,查看config/web.php里gii模块的allowedIPs和password配置)。
点击Model Generator,在Table Name栏输入post,Model Class填Post,点击Preview → Generate。
回到Gii首页,点击CRUD Generator:
Model Class:app\models\Post
Controller Class:app\controllers\PostController
View Path:@app/views/post
点击Preview → Generate,系统会自动创建控制器、视图文件夹及全部增删改查页面。
现在访问http://localhost/blog/web/index.php?r=post/index,就能看到空的博客列表页——这是真正可交互的后台起点。
调整入口路径并启用默认路由
把web/index.php剪切到项目根目录,重命名为index.php;同时把web/robots.txt也移过来。
打开新index.php,将两处路径前缀../改为./:
require __DIR__ . './vendor/autoload.php';
require __DIR__ . './vendor/yiisoft/yii2/Yii.php';
编辑config/web.php,在$config数组末尾的components内加入:
'assetManager' => [
'basePath' => '@webroot/assets',
'baseUrl' => '@web/assets'
],
最后设置默认首页跳转:在$config数组里添加一行
'defaultRoute' => 'post/index',
保存后访问http://localhost/blog/index.php,直接进入博客文章列表页。











