在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
早上在ruby-china发了个帖子,询问“现今PHP的框架中最接近RAILS的是什么?”大部分答曰"Yii”。所以晚上回来就来学下这个框架看看。
Yii 是一个基于组件、纯OOP的、用于开发大型 Web 应用的高性能 PHP 框架。
下载回来的软件包解压后结构如下:
第一部分为更新文档、许可(BSD许可,可以自由商用),升级文档以及README。 demos中有四个示例:a blog, the game Hangman, a basic “Hello, World!”, and a phone book。 framework 中是使用Yii必须的框架,核心部分。 requirements 主要是检查运行环境用的工具,另外还有一些小东西。
在WEB根目录下,建立yii的文件夹,放入framework 和requirements ,然后打开浏览器访问 http://localhost/yii/requirements,可以看到: 这是一个运行环境检查的程序,检查通过后就可以删掉requirements 了。
接着往下看: YII带了一个类似于rails的命令行生成器:yiic 。通过这个生成器可以帮助我们快速生成网站架构和MVC相关的文件! 好吧,这一条命令就是rails new 以及 rails g等等的衍生品。
1: E:\xampp\htdocs\yii\framework>yiic
2: Yii command runner (based on Yii v1.1.10)
3: Usage: E:\xampp\htdocs\yii\framework\yiic <command-name> [parameters...]
4:
5: The following commands are available:
6: - message
7: - migrate
8: - shell
9: - webapp
10:
11: To see individual command help, use the following:
12: E:\xampp\htdocs\yii\framework\yiic help <command-name>
创建我的第一个APP--运行: D:\xampp\htdocs>d:\xampp\php\php.exe d:\xampp\htdocs\framework\yiic webapp myblog 生成初始化的目录结构: 1: css/ 包含 CSS 文件 2: images/ 包含图片文件 3: themes/ 包含应用主题 4: protected/ 包含受保护的应用文件 5: yiic yiic 命令行脚本 6: yiic.bat Windows 下的 yiic 命令行脚本 7: yiic.php yiic 命令行 PHP 脚本 8: commands/ 包含自定义的 'yiic' 命令 9: shell/ 包含自定义的 'yiic shell' 命令 10: components/ 包含可重用的用户组件 11: Controller.php 所有控制器类的基础类 12: Identity.php 用来认证的 'Identity' 类 13: config/ 包含配置文件 14: console.php 控制台应用配置 15: main.php Web 应用配置 16: test.php 功能测试使用的配置 17: controllers/ 包含控制器的类文件 18: SiteController.php 默认控制器的类文件 19: data/ 包含示例数据库 20: schema.mysql.sql 示例 MySQL 数据库 21: schema.sqlite.sql 示例 SQLite 数据库 22: testdrive.db 示例 SQLite 数据库文件 23: extensions/ 包含第三方扩展 24: messages/ 包含翻译过的消息 25: models/ 包含模型的类文件 接下来就可以浏览了:
1: <?php
2: 3: // uncomment the following to define a path alias
4: // Yii::setPathOfAlias('local','path/to/local-folder');
5: 6: // This is the main Web application configuration. Any writable
7: // CWebApplication properties can be configured here.
8: return array( 9: 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 10: 'name'=>'My Web Application', 11: 12: // preloading 'log' component
13: 'preload'=>array('log'), 14: 15: // autoloading model and component classes
16: 'import'=>array( 17: 'application.models.*',
18: 'application.components.*',
19: ), 20: 21: 'modules'=>array( 22: // uncomment the following to enable the Gii tool
23: /*
24: 'gii'=>array( 25: 'class'=>'system.gii.GiiModule', 26: 'password'=>'Enter Your Password Here', 27: // If removed, Gii defaults to localhost only. Edit carefully to taste. 28: 'ipFilters'=>array('127.0.0.1','::1'), 29: ), 30: */ 31: ), 32: 33: // application components
34: 'components'=>array( 35: 'user'=>array( 36: // enable cookie-based authentication
37: 'allowAutoLogin'=>true, 38: ), 39: // uncomment the following to enable URLs in path-format
40: /*
41: 'urlManager'=>array( 42: 'urlFormat'=>'path', 43: 'rules'=>array( 44: '<controller:\w+>/<id:\d+>'=>'<controller>/view', 45: '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>', 46: '<controller:\w+>/<action:\w+>'=>'<controller>/<action>', 47: ), 48: ), 49: */ 50: 'db'=>array( 51: 'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db', 52: ), 53: // uncomment the following to use a MySQL database
54: /*
55: 'db'=>array( 56: 'connectionString' => 'mysql:host=localhost;dbname=testdrive', 57: 'emulatePrepare' => true, 58: 'username' => 'root', 59: 'password' => '', 60: 'charset' => 'utf8', 61: ), 62: */ 63: 'errorHandler'=>array( 64: // use 'site/error' action to display errors
65: 'errorAction'=>'site/error', 66: ), 67: 'log'=>array( 68: 'class'=>'CLogRouter', 69: 'routes'=>array( 70: array( 71: 'class'=>'CFileLogRoute', 72: 'levels'=>'error, warning', 73: ), 74: // uncomment the following to show log messages on web pages
75: /*
76: array( 77: 'class'=>'CWebLogRoute', 78: ), 79: */ 80: ), 81: ), 82: ), 83: 84: // application-level parameters that can be accessed
85: // using Yii::app()->params['paramName']
86: 'params'=>array( 87: // this is used in contact page
88: 'adminEmail'=>'[email protected]', 89: ), 90: ); 这里可以修改数据库 'db'=>array( 'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db', ), 默认使用了sqlite,改成mysql 如下: 'db'=>array( 'connectionString'=>'mysql:host=localhost;dbname=webapp, 'username'=>'root', 'password'=>'toor', ), 不得不说PHP的语法真丑,
工作流程描述如下:
配置Gii (Gii 自版本 1.1.2 可用) 为了使用 Gii,首先需要编辑文件 WebRoot/testdrive/protected/main.php,取消关于gii的注释部分: 1: 'gii'=>array( 2: 'class'=>'system.gii.GiiModule', 3: 'password'=>'test123', 4: // If removed, Gii defaults to localhost only. Edit carefully to taste. 5: 'ipFilters'=>array('127.0.0.1','::1'), 6: ),
然后,访问 URL http://localhost/myblog/index.php?r=gii 密码为上面这里配置的密码 test123。验证通过后可以看到:
创建一个model: 这里的tbl_user表是应用默认初始建立的用户表。 Generating code using template "D:\xampp\htdocs\framework\gii\generators\model\templates\default"... generated models\User.php done! 相关代码(D:\xampp\htdocs\myblog\protected\models\User.php)如下: 1: <?php
2: 3: /**
4: * This is the model class for table "tbl_user". 5: * 6: * The followings are the available columns in table 'tbl_user': 7: * @property integer $id 8: * @property string $username 9: * @property string $password 10: * @property string $email 11: */ 12: class User extends CActiveRecord 13: { 14: /**
15: * Returns the static model of the specified AR class. 16: * @param string $className active record class name. 17: * @return User the static model class 18: */ 19: public static function model($className=__CLASS__) 20: { 21: return parent::model($className); 22: } 23: 24: /**
25: * @return string the associated database table name 26: */ 27: public function tableName() 28: { 29: return 'tbl_user'; 30: } 31: 32: /**
33: * @return array validation rules for model attributes. 34: */ 35: public function rules() 36: { 37: // NOTE: you should only define rules for those attributes that
38: // will receive user inputs.
39: return array( 40: array('username, password, email', 'required'), 41: array('username, password, email', 'length', 'max'=>128), 42: // The following rule is used by search().
43: // Please remove those attributes that should not be searched.
44: array('id, username, password, email', 'safe', 'on'=>'search'), 45: ); 46: } 47: 48: /**
49: * @return array relational rules. 50: */ 51: public function relations() 52: { 53: // NOTE: you may need to adjust the relation name and the related
54: // class name for the relations automatically generated below.
55: return array( 56: ); 57: } 58: 59: /**
60: * @return array customized attribute labels (name=>label) 61: */ 62: public function attributeLabels() 63: { 64: return array( 65: 'id' => 'ID', 66: 'username' => 'Username', 67: 'password' => 'Password', 68: 'email' => 'Email', 69: ); 70: } 71: 72: /**
73: * Retrieves a list of models based on the current search/filter conditions. 74: * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. 75: */ 76: public function search() 77: { 78: // Warning: Please modify the following code to remove attributes that
79: // should not be searched.
80: 81: $criteria=new CDbCriteria; 82: 83: $criteria->compare('id',$this->id);
84: $criteria->compare('username',$this->username,true); 85: $criteria->compare('password',$this->password,true); 86: $criteria->compare('email',$this->email,true); 87: 88: return new CActiveDataProvider($this, array( 89: 'criteria'=>$criteria,
90: )); 91: } 92: } 生成 CRUD 代码 Generating code using template "D:\xampp\htdocs\framework\gii\generators\crud\templates\default"... generated controllers\UserController.php generated views\user\_form.php generated views\user\_search.php generated views\user\_view.php generated views\user\admin.php generated views\user\create.php generated views\user\index.php generated views\user\update.php generated views\user\view.php done! 这里生成了一个control 和 8个view。 control 代码: 1: <?php
2: 3: class UserController extends Controller 4: { 5: /**
6: * @var string the default layout for the views. Defaults to '//layouts/column2', meaning 7: * using two-column layout. See 'protected/views/layouts/column2.php'. 8: */ 9: public $layout='//layouts/column2';
10: 11: /**
12: * @return array action filters 13: */ 14: public function filters() 15: { 16: return array( 17: 'accessControl', // perform access control for CRUD operations 18: ); 19: } 20: 21: /**
22: * Specifies the access control rules. 23: * This method is used by the 'accessControl' filter. 24: * @return array access control rules 25: */ 26: public function accessRules() 27: { 28: return array( 29: array('allow', // allow all users to perform 'index' and 'view' actions 30: 'actions'=>array('index','view'), 31: 'users'=>array('*'), 32: ), 33: array('allow', // allow authenticated user to perform 'create' and 'update' actions 34: 'actions'=>array('create','update'), 35: 'users'=>array('@'), 36: ), 37: array('allow', // allow admin user to perform 'admin' and 'delete' actions 38: 'actions'=>array('admin','delete'), 39: 'users'=>array('admin'), 40: ), 41: array('deny', // deny all users 42: 'users'=>array('*'), 43: ), 44: ); 45: } 46: 47: /**
48: * Displays a particular model. 49: * @param integer $id the ID of the model to be displayed 50: */ 51: public function actionView($id) 52: { 53: $this->render('view',array( 54: 'model'=>$this->loadModel($id),
55: )); 56: } 57: 58: /**
59: * Creates a new model. 60: * If creation is successful, the browser will be redirected to the 'view' page. 61: */ 62: public function actionCreate() 63: { 64: $model=new User; 65: 66: // Uncomment the following line if AJAX validation is needed
67: // $this->performAjaxValidation($model);
68: 69: if(isset($_POST['User'])) 70: { 71: $model->attributes=$_POST['User'];
72: if($model->save()) 73: $this->redirect(array('view','id'=>$model->id)); 74: } 75: 76: $this->render('create',array( 77: 'model'=>$model,
78: )); 79: } 80: 81: /**
82: * Updates a particular model. 83: * If update is successful, the browser will be redirected to the 'view' page. 84: * @param integer $id the ID of the model to be updated 85: */ 86: public function actionUpdate($id) 87: { 88: $model=$this->loadModel($id); 89: 90: // Uncomment the following line if AJAX validation is needed
91: // $this->performAjaxValidation($model);
92: 93: if(isset($_POST['User'])) 94: { 95: $model->attributes=$_POST['User'];
96: if($model->save()) 97: $this->redirect(array('view','id'=>$model->id)); 98: } 99: 100: $this->render('update',array( 101: 'model'=>$model,
102: )); 103: } 104: 105: /**
106: * Deletes a particular model. 107: * If deletion is successful, the browser will be redirected to the 'admin' page. 108: * @param integer $id the ID of the model to be deleted 109: */ 110: public function actionDelete($id) 111: { 112: if(Yii::app()->request->isPostRequest) 113: { 114: // we only allow deletion via POST request
115: $this->loadModel($id)->delete(); 116: 117: // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
118: if(!isset($_GET['ajax'])) 119: $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin')); 120: } 121: else 122: throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
123: } 124: 125: /**
126: * Lists all models. 127: */ 128: public function actionIndex() 129: { 130: $dataProvider=new CActiveDataProvider('User');
131: $this->render('index',array( 132: 'dataProvider'=>$dataProvider,
133: )); 134: } 135: 136: /**
137: * Manages all models. 138: */ 139: public function actionAdmin() 140: { 141: $model=new User('search');
142: $model->unsetAttributes(); // clear any default values
143: if(isset($_GET['User'])) 144: $model->attributes=$_GET['User'];
145: 146: $this->render('admin',array( 147: 'model'=>$model,
148: )); 149: } 150: 151: /**
152: * Returns the data model based on the primary key given in the GET variable. 153: * If the data model is not found, an HTTP exception will be raised. 154: * @param integer the ID of the model to be loaded 155: */ 156: public function loadModel($id) 157: { 158: $model=User::model()->findByPk($id); 159: if($model===null) 160: throw new CHttpException(404,'The requested page does not exist.');
161: return $model; 162: } 163: 164: /**
165: * Performs the AJAX validation. 166: * @param CModel the model to be validated 167: */ 168: protected function performAjaxValidation($model) 169: { 170: if(isset($_POST['ajax']) && $_POST['ajax']==='user-form') 171: { 172: echo CActiveForm::validate($model); 173: Yii::app()->end(); 174: } 175: } 176: } 177: VIEW: update.php的代码, 1: <?php
2: $this->breadcrumbs=array( 3: 'Users'=>array('index'), 4: $model->id=>array('view','id'=>$model->id), 5: 'Update',
6: ); 7: 8: $this->menu=array( 9: array('label'=>'List User', 'url'=>array('index')), 10: array('label'=>'Create User', 'url'=>array('create')), 11: array('label'=>'View User', 'url'=>array('view', 'id'=>$model->id)), 12: array('label'=>'Manage User', 'url'=>array('admin')), 13: ); 14: ?>
15: 16: <h1>Update User <?php echo $model->id; ?></h1> 17: 18: <?php echo $this->renderPartial('_form', array('model'=>$model)); ?> 代码结构跟Rails惊人相似,而且连view都分离出了一个_form.php来给create.php和update.php复用。Rails的dry的理念已经贯穿了Yii。 可以访问了:http://localhost/myblog/index.php?r=User 自动实现了CRUD的所有代码,并且还带search功能。还是很方便的,很节约人力的!
Yii 应用的典型流程 1. 用户访问 http://www.example.com/index.php?r=post/show&id=1 Web 服务器执行入口脚本index.php 来处理该请求。
应用的核心组件
Yii预定义了一套核心应用组件提供Web应用程序的常见功能。例如,request组件用于解析用户请求和提供信息,如网址,cookie。在几乎每一个方面,通过配置这些核心组件的属性,我们都可以更改Yii的默认行为。
路由 用户请求一个特定的 controller 和 action 用术语即为 route. 一个 route 由一个 controller ID 和一个 action ID 连结而成,二者中间以斜线分隔. 例如, route post/edit 引用的是 PostController 和它的 edit action. 默认情况下, URLhttp://hostname/index.php?r=post/edit 将请求此 controller 和 action.
自版本 1.0.3, 一个应用可以包含 模块. 一个 module 中的 controller 的 route 格式是 moduleID/controllerID/actionID.
使用 Form Builder 当创建 HTML 表单时,经常我们发现我们在写很多重复而且在不同项目中很难重用的视图代码。例如,对于每个输入框,
声明关联
1: class Post extends CActiveRecord
2: { 3: public function relations()
4: { return array(
5: 'author'=>array(self::BELONGS_TO, 'User', 'author_id'), 6: 'categories'=>array(self::MANY_MANY, 'Category', 7: 'tbl_post_category(post_id, category_id)'), 8: ); 9: } 10: } 11: 12: class User extends CActiveRecord
13: { 14: public function relations()
15: { return array(
16: 'posts'=>array(self::HAS_MANY, 'Post', 'author_id'), 17: 'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'), 18: ); 19: } 20: }
开发流程 1. 创建目录结构。
嗯,就到这里吧,其他的看直接看手册比较合适。另外研读代码的同学可以直接看安装包里带的几个DEMOS,试做的可以跟 Yii Blog Book v1.1.pdf 的教程 。另外介绍下中文论坛。
本文内容,大部分来源官方文档。 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论