日期:2014-05-17  浏览次数:20581 次

PHP框架YII笔记之1
1 用脚手架安装yiic,注意把framework下的yiic和php下的php.exe放到PATH中去,
假设应用目录为yiidemo,则先
cd yiidemo
yiic webapp demo(这个是应用程序的名)
之后会产生框架


2 创建controller
   cd yiidemo
   yiic shell
  此时可以help去看帮助
先产生的controller
   controller message(controller名) helloworld(方法名)
  默认在protectd目录下也产生controller,并且views目录下也有同controller
名相同的views文件

运行:
http://localhost:8082/myphp/yiidemo/index.php?r=message/helloWorld

   往视图中传递参数也是一样的:
  $theTime = date("D M j G:i:s T Y");
$this->render('helloWorld',array('time'=>$theTime));
VIEW中:
<?php echo $time; ?>


3 yii的HTML帮助类的连接:
   <?php echo CHtml::link("Goodbye",array('message/goodbye'));?>
   出来的会是一个LINK了,第一个参数是连接的文字,第2个数组是
key-value,分别是controller/method

4 yii的单元测试
   测试文件放在protected/tests/unit/中
   一般是以Action+Test命名,比如MessageTest.class
,如果要测试的方法为actionHelloworld(),则测试方法为
testActionHelloworld().

  功能测试文件放在protected/tests/functional中

5 单元测试步骤
  1)安装phpunit
   pear channel-discover pear.phpunit.de
    pear install phpunit/PHPUnit

(注意升级下pear upgrade -all)
  2)下载selenium RC SERVER
  3) 修改 test目录下的WebTestCase.php,设置为
    define('TEST_BASE_URL','http://localhost:8082/myphp/yiidemo/index-

test.php/');
  4) 启动selenium server
 
  5) 测试开始
    cd protected/tests/
    phpunit functional/SiteTest.php
   会自动打开IE,FIREFOX去测试,可以到test\phpunit.xml中去修改浏览器设置

6)TDD
  每写一个类,则
  phpunit unit/XXXX.PHP测试下
   
例子
<?
Yii::import('application.controllers.MessageController');
class MessageTest extends CTestCase
{
public function testRepeat()
{

$message = new MessageController('messageTest');
$yell = "Hello, Any One Out There?";
$returnedMessage = $message->repeat($yell);
$this->assertEquals($returnedMessage, $yell);
}
}

?>

7 数据库连接
  $connection=new CDbConnection($dsn,$username,$password);
  SQLite: sqlite:/path/to/dbfile
? MySQL: mysql:host=localhost;dbname=testdb
? PostgreSQL: pgsql:host=localhost;port=5432;dbname=testdb
? SQL Server: mssql:host=localhost;dbname=testdb
? Oracle: oci:dbname=//localhost:1521/testdb
配置文件在
  /protected/config/main.php
  修改为MYSQL配置
   // application components
'components'=>array(

'db'=>array(
'connectionString' => 'mysql:host=127.0.0.1;dbname=trackstar_dev',
'emulatePrepare' => true,
'username' => 'your_db_user_name',
'password' => 'your_db_password',
'charset' => 'utf8',
),
),
  使用时:Yii::app()->db


8 启动GII
  gii是快速构建的工具之一,实际上就是一个网页的脚手架产生工具
   1)配置
    protected\config\main.php
     增加:
'modules'=>array(
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'[自己定的密码]',
),
),


  2) 在数据库中建立表后,到GII中产生MODEL类
  3)继续单元测试
      <?php
class ProjectTest extends CDbTestCase
{
public function testCRUD()
{
//Create a new project
$newProject=new Project;
$newProjectName = 'Test Project 1';
$newProject->setAttributes(
array(
'name' => $newProjectName,
'description' => 'Test project number one',
'create_time' => '2010-01-01 00:00:00',
'create_user_id' => 1,
'update_time' => '2010-01-01 00:00:00',
'updat