您的位置:首页 > 编程语言 > PHP开发

Yii学习笔记(入门)

2015-09-08 11:41 579 查看
<?php
namespace app\models;

use yii\db\ActiveRecord;

class A extends ActiveRecord
{

}


hello, I am only page.


1、初始化应用

下载yii框架(基本版下载地址,传送门),解压到你的php源码路径下,

访问http://localhost/basic/web/index.php,进入yii的启动页面。

如果提示你未安装openssl的话,去你的php.ini中修改你的配置文件,当然,提示其他扩展未安装也是如此。

2、创建自己的控制器

以下代码为初始化Yii控制器所需要的代码:

<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;

class IndexController extends Controller
{
public function actionIndex()
{
echo "this is my first yii page.";
}
}
访问http://localhost/basic/web/index.php?r=index/index,显示“this is my first yii page“。

3、创建视图

在basic/views目录下创建视图,文件夹名与控制器名相对应

本例中文件夹位置应该为/basic/views//index下

在文件夹中创建要显示的视图,后缀名为php,本例为创建hello.php

内容很简单

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf8">
<title>
Yii Home
</title>
</head>

<body>
<h1>Hello, this is my first view page.</h1>
<body>
</html>
在控制器中写入

public function actionHome()
{
return $this->renderPartial("hello");
}
访问http://localhost/basic/web/index.php?r=index/Home,即可显示相应的视图文件。
4、加载模板文件
在/basic/views/layouts下新建模板文件common.php
</pre><pre name="code" class="php"><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf8">
<title>
Yii Home
</title>
</head>

<body>
<h1>$contents</h1>
<body>
</html>

在views/index下新建文件only.php

Hello I'm only page.


在控制器中写入

public $layout = "common.php";
public function actionLayout()
{
return $this->render("index");//render里的数据会被识别为$contents
}
访问
http://localhost/basic/web/index.php?r=index/lay
二者即可一起显示出来,使用模板可以大大减少代码的重复率。
5、从控制器向视图传递数据

$data['name'] = "username";
$data['password'] = "password";
//return $this->renderPartial("index",$data);
return $this->render("index",$data);


在模板页即可直接使用$name和$password来传递你需要传递的数据。

6、配置数据库

数据库配置在/basic/web/config/db.php中,配置项一目了然,在这里不再赘述。

7、创建模型

在/basic/web/models下新建A.php(你的表名)

代码如下

<?php namespace app\models; use yii\db\ActiveRecord; class A extends ActiveRecord { }
你可能要问为什么什么都没有写,其实是因为它继承了ActiveRecord类,Yii已经赋予它了许多实用的方法。

8、在控制器中使用模型
use app\models\A;//顶部加上

//控制器类中代码:
//数据库查询
public function actionDb()
{
//$sql = "select * from A";
//$results = A::findBySql($sql)->all();
$results = A::find()->where(["between","id",1,3])->asArray()->all();
print_r($results);
}

//删除数据
public function actionDel()
{
$results = A::find()->all();
$results[3]->delete();
}

//批量删除数据
public function actionDelall()
{
A::deleteAll("id=:id",[':id'=>3]);//你在这里当然可以使用>、<、!=这些符号来选择你的数据
}
好了,今天只学习到了这里,明天继续。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  yii