以下是一个简单的Yii框架PHP实例,我们将通过一个简单的博客系统来展示如何使用Yii框架进行开发。
1. 创建项目结构
我们需要创建项目的基本结构。在命令行中,执行以下命令:

```bash
yii new blog
```
这将创建一个名为`blog`的新项目。
2. 配置数据库
在`config/db.php`文件中配置数据库连接信息:
```php
return [
'class' => 'yii""db""Connection',
'dsn' => 'mysql:host=localhost;dbname=your_database',
'username' => 'your_username',
'password' => 'your_password',
'charset' => 'utf8',
];
```
确保替换`your_database`、`your_username`和`your_password`为实际的数据库信息。
3. 创建模型
在`models`目录下创建一个新的模型`Post.php`:
```php
namespace app""models;
use Yii;
class Post extends ""yii""db""ActiveRecord
{
public static function tableName()
{
return 'posts';
}
public function rules()
{
return [
[['title', 'content'], 'required'],
[['title', 'content'], 'string'],
];
}
}
```
4. 创建控制器
在`controllers`目录下创建一个新的控制器`PostController.php`:
```php
namespace app""controllers;
use app""models""Post;
use yii""data""ActiveDataProvider;
use yii""web""Controller;
use yii""web""NotFoundHttpException;
use yii""filters""VerbFilter;
class PostController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
'query' => Post::find(),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionCreate()
{
$model = new Post();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
protected function findModel($id)
{
if (($model = Post::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
```
5. 创建视图
在`views/post`目录下创建以下视图文件:
- `index.php`
- `view.php`
- `create.php`
- `update.php`
每个视图文件包含用于显示、创建、更新和删除文章的HTML代码。
6. 配置路由
在`config/web.php`文件中配置路由:
```php
return [
'controllerMap' => [
'gii' => 'yii""gii""Module',
],
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'post/index' => 'post/index',
'post/view/
'post/create' => 'post/create',
'post/update/
'post/delete/
],
],
],
];
```
7. 运行应用
在命令行中,执行以下命令来运行应用:
```bash
php ./yii serve
```
现在,你可以通过访问`http://localhost/index.php/post/index`来查看你的博客系统了。
以上是一个简单的Yii框架PHP实例,希望对你有所帮助。









