最近在学PHP的Yii框架,记录一下学习收获方便以后查看。
一、Yii框架采用的是MVC架构模式分:Model\View\Controler 三大块。
什么事MVC模式?简单实用地说:如果视图这里看的有点莫名其妙的时候先去看下控制器。视图的展现与控制器息息相关。视图的逻辑不清的地方在控制器会有答案。
二、访问数据库有两种方式,
1、对象数据库方式,主要是基于Yii框架的ActiveRecord类来实现,
eg:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "EquipmentOfProperty".
*
* @property string $EquipmentOfPropertyId
* @property string $PropertyId
* @property string $EquipmentId
* @property int $SortOrder
*/
class EquipmentOfProperty extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'EquipmentOfProperty';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['EquipmentOfPropertyId', 'PropertyId', 'EquipmentId'], 'required'],
[['EquipmentOfPropertyId', 'PropertyId', 'EquipmentId', 'SortOrder'], 'integer'],
[['EquipmentOfPropertyId'], 'unique'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'EquipmentOfPropertyId' => Yii::t('app', 'Equipment Of Property ID'),
'PropertyId' => Yii::t('app', 'Property ID'),
'EquipmentId' => Yii::t('app', 'Equipment ID'),
'SortOrder' => Yii::t('app', 'Sort Order'),
];
}
}
优点:1)这种方式访问数据库简单,对于一些对数据库不熟悉的人容易上手。
2)较大吻合面向对象编程思想,能容易理解
缺点:创建对象比较多,创建过程中耗费时间与系统资源,不是很合适访问量非常大响应度非常高的服务。
2、直接访问数据库模式,主要是基于Yii框架的SqlDataProvider类来实现,
<?php
namespace app\modules\process\models\search;
use app\modules\process\models\ProductionRule;
use Yii;
class ProductionRuleDataProvider extends ProductionRule
{
public function search($params)
{
$sql = 'SELECT RuleId,Description,Version FROM ProductionRule';
$count = Yii::$app->db->createCommand('SELECT COUNT(RuleId) FROM ProductionRule')->queryScalar();
$dataProvider = new \yii\data\SqlDataProvider([
'pagination' => false,
'sql' => $sql,
'key' => 'RuleId',
'totalCount' => $count,
'sort' => [
'attributes' => [
'PublishedDate' => [
'default' => SORT_DESC,
],
],
'defaultOrder' => [
'PublishedDate' => SORT_DESC,
],
],
]);
return $dataProvider;
}
private function findProductionRule($id){
return ProductionRule::findOne(['RuleId'=>$id])!==null;
}
public function firstKey($id){
try {
if($this->findProductionRule($id)) return $id;
$command = Yii::$app->db->createCommand('SELECT RuleId FROM ProductionRule');
$id = $command->queryScalar();
if(isset($id) && $id !== false) return $id;
} catch (Exception $exc) {
\app\helpers\Verification::throwException($e->getMessage());
}
return 0;
}
}
优点:高效
缺点:必须对SQL语句,对数据库后台表结构比较清楚
三、PHP严格区分大小写,数据库都必须一致
如果以前使用其他语言的时候不太注意大小写的童鞋这点会比较不适应,而且容易出现问题。
譬如:数据库字段是EquipmentId,代码中写的是EquipmentID则会成为是别不到的字段而报错。