2测试工作,注意事项

测试过程中有时候需要生成大量的假数据,faker 是一个生成假数据的类库.Yii2.0已经集成该类库yii2-faker,不用再下载了。

新建项目 composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic
目录:

本文实例讲述了YII Framework框架使用YIIC快速创建YII应用的方法。分享给大家供大家参考,具体如下:

这是一个系列文章,分3部分:
1、准备工作--Yii2高级模板的安装,以及编写一个类(方法)和一个model的RETful
2、测试工作--单元测试和API(REST规范的)测试
3、力争上游--覆盖率、基础概念、引用文献等

以Yii2.0 advanced版为例:

1. consoleconfigmain-local.php中添加一条配置信息

'controllerMap' => [ 'fixture' => [ 'class' => 'yiifakerFixtureController', ],],

注意顶部,定义tests测试目录的位置的代码。在consoleconfigbootstrap.php中添加

Yii::setAlias('@tests', dirname . '/tests');

2. 创建生成假信息的模版文件

在tests目录下面依次新建unit/templates/fixtures目录,然后在fixtures目录下新建blogs.php文件。内容如下:

<?php// users.php file under template path (by default @tests/unit/templates/fixtures)/** * @var $faker FakerGenerator * @var $index integer */return [ 'title' => $faker->title, 'content' => $faker->realText, 'views' => $faker->firstName, 'is_delete' => $faker->boolean, 'created_at' => $faker->date($format = 'Y-m-d', $max = 'now'), 'updated_at' => $faker->date($format = 'Y-m-d', $max = 'now'), 'file' => $faker->imageUrl($width = 640, $height = 480), 'file2' => $faker->imageUrl($width = 640, $height = 480),];

3. 打开命令行,执行生成假记录命令

php yii fixture/generate users --count=10

图片 1git bash

生成的假数据位于testsunitfixturesdatablogs.php,打开如下,有了假数据内容,剩下的就好办了

<?phpreturn [ [ 'title' => 'Miss', 'content' => 'King, with an anxious look at it!' This speech caused a remarkable sensation among the people that walk with their fur clinging close to her, still it had VERY long claws and a crash of broken.', 'views' => '丽丽', 'is_delete' => true, 'created_at' => '1977-04-04', 'updated_at' => '2013-06-04', 'file' => 'https://lorempixel.com/640/480/?42094', 'file2' => 'https://lorempixel.com/640/480/?90710', ], [ 'title' => 'Mrs.', 'content' => 'As soon as look at me like that!' But she waited patiently. 'Once,' said the Queen. 'Their heads are gone, if it please your Majesty,' said the one who had spoken first. 'That's none of YOUR.', 'views' => '帅', 'is_delete' => true, 'created_at' => '1996-08-25', 'updated_at' => '2012-04-09', 'file' => 'https://lorempixel.com/640/480/?44425', 'file2' => 'https://lorempixel.com/640/480/?16747', ], ...]

1.config/web.php 修改

yii提供了强大的命令行工具来快速的创建相关组件和应用。</span> 

本文是第二部分,主要是单元测试和API测试。

1.1 log 用于打印输出

cd进入yii/framework框架的根目录。

单元测试

1、执行vendor/bin/codecept generate:cest -c common unit CustomeString
新建了commontestsunitCustomeStringCest.php,开始写测试代码了,增加内容:

    public function tryToTest(UnitTester $I)
    {
        $len = 10;
        $prefix = 'pre';

        $string = CustomString::generateCode($len, $prefix);
        expect(strlen($string))->equals($len   3);
        expect(substr($string, 0, 3))->equals($prefix);
        //等效于 expect($string)->startsWith($prefix);
       //这就是codeception的强大之处,封装了几乎所有测试需要的,官方说90% ,且不希望你重复造轮子
    }

2、执行vendor/bin/codecept run -c common
我们可以在命令终端看到测试运行的情况。

至此,恭喜你,已经利用codeception进行了某个类的(方法的)测试。

我们继续来书写如何测试一个model:
4、执行vendor/bin/codecept generate:test -c common unit models/News
新建一个commontestunitmodelsNewsTest.php,我们仿照LoginFormTest.php,编写NewsTest.php:

<?php

namespace commontestsmodels;

use commonfixturesNewsFixture;
use commonmodelsNews;

class NewsTest extends CodeceptionTestUnit
{
    public function _fixtures()
    {
        return [
            'news' => [
                'class' => NewsFixture::class,
                'dataFile' => codecept_data_dir() . 'news.php',
            ],
        ];
    }

    public function testValidate()
    {
        $model = new News(['title' => 'one title']);
        expect('model should create successfully', $model->save())->true();

        $model = new News(['code' => Yii::$app->security->generateRandomString(33)]);
        expect('model should create fail', $model->save())->false();
        expect('error message should be set', $model->errors)->hasKey('code');

        $model = new News(['title' => null]);
        expect('model should create fail', $model->save())->false();
        expect('error message should be set', $model->errors)->hasKey('title');

        $model = new News(['title' => Yii::$app->security->generateRandomString(256)]);
        expect('model should create fail', $model->save())->false();
        expect('error message should be set', $model->errors)->hasKey('title');
    }

    public function testData()
    {
        $data = News::find()->where(['title' => 'This is a title'])->one();
        expect(count($data))->equals(1);
    }
}

5、因为需要用到NewsFixture::classcodecept_data_dir() . 'news.php'
所以我们需要在common的fixtures下新建NewFixture.php
(具体位置无所谓,只需要保证命名空间是commonfixtures):

<?php
namespace commonfixtures;

use yiitestActiveFixture;

class NewsFixture extends ActiveFixture
{
    public $modelClass = 'commonmodelsNews';
}

然后在commontests_data下新建news.php,自己添加一些数据:

<?php

return [
    [
        'code' => 'abcdefg',
        'title' => 'This is a title',
        'content' => '<p>some Content</p>',
        'status' => 0,
        'created_at' => 1402312317,
        'updated_at' => 1402312317,
        'created_by' => 1,
        'updated_by' => 1,
    ],
    [
        'code' => '22222',
        'title' => 'This is second title',
        'content' => '<p>some Content</p>',
        'status' => 1,
        'created_at' => 1402312317,
        'updated_at' => 1402312317,
        'created_by' => 1,
        'updated_by' => 1,
    ],
];

6、执行vendor/bin/codecept run -c common,查看测试运行情况。
至此,单元测试算告一段落。

单元测试,基本上就是对自定义的类的(方法的)测试,还有model的一些测试。
当有新的自定义类或者model时,类似上述新增测试用例即可。

7、 补充:
由于codeception包含3种格式的测试文件:Cept, Cest and Test

Cept are written as narrative scenarios. To make a PHP file a valid scenario, its name should have a Cept suffix.
描述行语言,文件后缀是Cept,常用于功能、验收还有API测试。
Cest combines scenario-driven test approach with OOP design. In case you want to group a few testing scenarios into one, you should consider using Cest format.
Codeception can also execute PHPUnit test files for unit testing。
注意Test格式时,方法名需要以test开头,另外两种格式不要求。

上述的例子是Test格式,当然可以写成Cept和Cest,实质上等效。
我习惯单元测试用Cest,API测试用Cept。
执行vendor/bin/codecept generate:cest -c common unit models/News
新建一个commontestunitmodelsNewsCest.php,等效代码如下:

<?php

namespace commontestsunitmodels;

use commonfixturesNewsFixture;
use commonmodelsNews;
use commontestsUnitTester;

class NewsCest
{
    public function _before(UnitTester $I)
    {
        $I->haveFixtures([
            'news' => [
                'class' => NewsFixture::class,
                'dataFile' => codecept_data_dir() . 'news.php',
            ],
        ]);
    }

    public function _after(UnitTester $I)
    {
    }

    // tests
    public function tryToTestValidate(UnitTester $I)
    {
        $model = new News(['title' => 'one title']);
        expect('model should create successfully', $model->save())->true();

        $model = new News(['code' => Yii::$app->security->generateRandomString(33)]);
        expect('model should create fail', $model->save())->false();
        expect('error message should be set', $model->errors)->hasKey('code');

        $model = new News(['title' => null]);
        expect('model should create fail', $model->save())->false();
        expect('error message should be set', $model->errors)->hasKey('title');

        $model = new News(['title' => Yii::$app->security->generateRandomString(256)]);
        expect('model should create fail', $model->save())->false();
        expect('error message should be set', $model->errors)->hasKey('title');
    }

    public function toTestData()
    {
        $data = News::find()->where(['title' => 'This is a title'])->one();
        expect(count($data))->equals(1);
    }
}
1.2 urlManager

1.config/web.php 修改

#### 1.1 log 用于打印输出
使用方法:Yii::log('your message', 'error', 'orders');
yii::trace("$msg",'$category')
yii::error($msg,$category)
'log' => [
                'traceLevel' => 0, //YII_DEBUG ? 3 : 0,
                'flushInterval' => 1,   //
                'targets' => [
                    [

                        'class' => 'yiilogFileTarget',
                        'levels' => ['error', 'warning'],
                        'exportInterval' => 1,
                        'logFile' => '@app/runtime/logs/bb.log',
                        /*
                        'logFile' => '@app/runtime/logs/bb.log',
                        'exportInterval' => 100,
                        'class' => 'yiilogFileTarget',
                        //'levels' => ['error', 'warning'],
                        'categories' => [
                            'yiidb*',
                            'yiiwebHttpException:*',
                        ],
                        'except' => [
                            'yiiwebHttpException:404',
                        ],
                        */
                    ],
                     [
                        'class' => 'yiilogFileTarget',
                        'categories' => ['lucky'],
                        'levels' => ['error'],
                        'logVars' => [],   //!!! disable global variables
                        'logFile' => '@app/runtime/logs/lucky-error.log',
                    ],
                    [
                       'class' => 'yiilogFileTarget',
                       'categories' => ['lucky'],
                       'levels' => ['warning'],
                       'logVars' => [],   //!!! disable global variables
                       'logFile' => '@app/runtime/logs/lucky-warning.log',
                   ],
                    [
                       'class' => 'yiilogFileTarget',
                       'categories' => ['lucky'],
                       'levels' => ['trace'],
                       'logVars' => [],   //!!! disable global variables
                       'logFile' => '@app/runtime/logs/lucky-trace.log',
                   ],
                    [
                       'class' => 'yiilogFileTarget',
                       'categories' => ['money'],
                       'levels' => ['info'],
                       'logVars' => [],   //!!! disable global variables
                       'logFile' => '@app/runtime/logs/money.log',
                   ],
                    [
                        'class' => 'yiilogFileTarget',
                        'categories' => ['promotion'],
                        'levels' => ['error', 'warning','trace'],
                        'logVars' => [],   //!!! disable global variables
                        'logFile' => '@app/runtime/logs/promotion-data.log',
                    ],
                    [
                        'class' => 'yiilogFileTarget',
                        'categories' => ['agent'],
                        'levels' => ['error', 'warning','trace'],
                        'logVars' => [],   //!!! disable global variables
                        'logFile' => '@app/runtime/logs/agent-data.log',
                    ],
                ],
            ],

执行

功能和验收测试

由于前后端分离,这里不再介绍codeception的功能和验收测试。
你可以查看frontend/tests/下的functional和accptance部分。
关于前端测试,可以参看CodeceptJS

1.2 urlManager

urlManager 用于管理 控制器路由访问方式 不添加下面语句
访问方式 http://localhost:8887/index.php?r=site/about
访问方式 http://localhost:8887/site/about

    'urlManager' => [
        'class' => 'yiiwebUrlManager',
        'showScriptName' => false,
        'enablePrettyUrl' => true,
        'enableStrictParsing' => false,
        'rules' => [
            ['class' => 'yiirestUrlRule', 'controller' => 'authapi'],

        ],
    ],
  1. faker 生成假数据
    configconsole.php 中添加一条配置信息
  2. configconsole.php 中添加一条配置信息
    'controllerMap' => [ 'fixture' => [ 'class' => 'yiifakerFixtureController', ],],

注意顶部,定义test测试目录的位置的代码。
Yii::setAlias('@tests', dirname(DIR) . '/tests');

# php yiic
Yii command runner (based on Yii v1.1.8)
Usage: yiic <command-name> [parameters...]

The following commands are available:
 - message
 - migrate
 - shell
 - webapp

To see individual command help, use the following:
  yiic help <command-name>

API测试

接口的自动化测试,这里是一个方案,具体参看WebServices,
Postman的自动化接口测试也是一个不错的方案,有时间再整理。

首先要执行vendor/bin/codecept g:suite api -c blog,输出:

Helper blogtestsHelperApi was created in /home/lijun/works/yii-application/blog/tests/_support/Helper/Api.php
Actor ApiTester was created in /home/lijun/works/yii-application/blog/tests/_support/ApiTester.php
Suite config api.suite.yml was created.

Next steps:
1. Edit api.suite.yml to enable modules for this suite
2. Create first test with generate:cest testName ( or test|cept) command
3. Run tests of this suite with codecept run api command
Suite api generated

按照提示继续下面的步骤:
1)、编辑api.suite.yml,启用REST,且依赖Yii2。如下:

#suite_namespace: blogtestsapi
actor: ApiTester
modules:
    enabled:
        - blogtestsHelperApi
        - REST:
            #url:
            depends: Yii2
            #part: Json

2)、执行vendor/bin/codecept g:cept api -c blog News创建测试文件blogtestsapiNewsCept.php。

<?php

use blogtestsApiTester;
use CodeceptionUtilHttpCode;

$I = new ApiTester($scenario);

//create
$data = ['code' => 'code1', 'title' => 'first title', 'content' => 'first content'];
$I->wantTo('create a news');
$I->sendPOST('/news', $data);
$I->seeResponseCodeIs(HttpCode::CREATED);
$I->seeResponseIsJson();
//{"code":"code1","title":"first title","content":"first content","id":16}
$I->seeResponseContainsJson($data);

//view
$I->wantTo('view a news');
$id = $I->grabDataFromResponseByJsonPath('$.id')[0];
$I->sendGET('/news/' . $id);
$I->seeResponseCodeIs(HttpCode::OK);
$I->seeResponseIsJson();
$I->seeResponseMatchesJsonType([
    'id' => 'integer',
    'title' => 'string',
    'content' => 'string|null',
]);

//update
$I->wantTo('update news');
$id = $I->grabDataFromResponseByJsonPath('$.id')[0];
$I->sendPUT('/news/' . $id, ['content' => 'updated content']);
$I->seeResponseCodeIs(HttpCode::OK);
$I->seeResponseContainsJson(['content' => 'updated content']);

//index
$I->wantTo('list news');
$I->sendGET('/news');
$I->seeResponseCodeIs(HttpCode::OK);
//{"items":[{"id":49,"code":"code1","title":"first title","content":"first content","status":0,"created_at":0,"created_by":0,"updated_at":0,"updated_by":0}],"_links":{"self":{"href":"http://localhost/index-test.php/news?page=1"}},"_meta":{"totalCount":1,"pageCount":1,"currentPage":1,"perPage":20}}
$I->seeResponseJsonMatchesJsonPath('$.items..title');
$I->seeResponseJsonMatchesXpath('//_meta//totalCount');


//delete
$I->wantTo('delete a news');
$id = $I->grabDataFromResponseByJsonPath('$.items..id');
$I->sendDELETE('/news/' . $id[0]);
$I->seeResponseCodeIs(HttpCode::NO_CONTENT);

//index
$I->wantTo('list empty news');
$I->sendGET('/news');
$I->seeResponseCodeIs(HttpCode::OK);

3)、运行测试vendor/bin/codecept run -c blog
提示需要安装flow/jsonpath,执行composer require -dev "flow/jsonpath"。待安装之后再次执行测试即可。

至此,REST的API测试完成。
Yii2下使用codeception进行单元测试和API测试到此告一段落,后面可以继续熟悉codeception的强大吧。

上一篇:准备工作
下一篇:力争上游

可以看到

yiic的基本命令参数规则

yiic <command-name> [parameters...]

command-name对应的有
 - message
 - migrate
 - shell
 - webapp

如果要查看具体的命令的功能可以用

yiic help <command-name>

例如:

php yiic shell

1.php yiic webapp

执行 php yiic help webapp

/* 
USAGE 
 yiic webapp <app-path> 
DESCRIPTION 
 This command generates an Yii Web Application at the specified location. 
PARAMETERS 
 * app-path: required, the directory where the new application will be created. 
  If the directory does not exist, it will be created. After the application 
  is created, please make sure the directory can be accessed by Web users. 
*/ 

在指定的位置创建一个基于yii的完整结构的webapp。app-path是webapp的存放目录。如果目录不存在会被创建。

例如:

/yii/framework# php yiic webapp ../../testwebap
 Create a Web application under '/home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap'? [Yes|No] Yes
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap
  generate index-test.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/themes
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/themes/classic
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/themes/classic/views
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/themes/classic/views/layouts
  generate themes/classic/views/.htaccess
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/themes/classic/views/site
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/themes/classic/views/system
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/css
  generate css/ie.css
  generate css/bg.gif
  generate css/screen.css
  generate css/form.css
  generate css/print.css
  generate css/main.css
  generate index.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/assets
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/models
  generate protected/models/LoginForm.php
  generate protected/models/ContactForm.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/components
  generate protected/components/UserIdentity.php
  generate protected/components/Controller.php
  generate protected/yiic.bat
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/controllers
  generate protected/controllers/SiteController.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/migrations
  generate protected/yiic
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/data
  generate protected/data/testdrive.db
  generate protected/data/schema.mysql.sql
  generate protected/data/schema.sqlite.sql
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/config
  generate protected/config/test.php
  generate protected/config/console.php
  generate protected/config/main.php
  generate protected/.htaccess
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/layouts
  generate protected/views/layouts/column1.php
  generate protected/views/layouts/column2.php
  generate protected/views/layouts/main.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/site
  generate protected/views/site/contact.php
  generate protected/views/site/login.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/site/pages
  generate protected/views/site/pages/about.php
  generate protected/views/site/index.php
  generate protected/views/site/error.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/messages
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/tests
  generate protected/tests/bootstrap.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/tests/fixtures
  generate protected/tests/phpunit.xml
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/tests/report
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/tests/unit
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/tests/functional
  generate protected/tests/functional/SiteTest.php
  generate protected/tests/WebTestCase.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/runtime
  generate protected/yiic.php
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/extensions
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/commands
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/commands/shell
   mkdir /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/images

Your application has been created successfully under /yii_dev/testwebap.

生成的目录结构如下

testwebap
│   ├── assets
│   ├── css
│   ├── images
│   ├── index.php
│   ├── index-test.php
│   ├── protected
│   └── themes
详细目录结构如下
├── assets
├── css
│   ├── bg.gif
│   ├── form.css
│   ├── ie.css
│   ├── main.css
│   ├── print.css
│   └── screen.css
├── images
├── index.php
├── index-test.php
├── protected
│   ├── commands
│   │   └── shell
│   ├── components
│   │   ├── Controller.php
│   │   └── UserIdentity.php
│   ├── config
│   │   ├── console.php
│   │   ├── main.php
│   │   └── test.php
│   ├── controllers
│   │   └── SiteController.php
│   ├── data
│   │   ├── schema.mysql.sql
│   │   ├── schema.sqlite.sql
│   │   └── testdrive.db
│   ├── extensions
│   ├── messages
│   ├── migrations
│   ├── models
│   │   ├── ContactForm.php
│   │   └── LoginForm.php
│   ├── runtime
│   ├── tests
│   │   ├── bootstrap.php
│   │   ├── fixtures
│   │   ├── functional
│   │   │   └── SiteTest.php
│   │   ├── phpunit.xml
│   │   ├── report
│   │   ├── unit
│   │   └── WebTestCase.php
│   ├── views
│   │   ├── layouts
│   │   │   ├── column1.php
│   │   │   ├── column2.php
│   │   │   └── main.php
│   │   └── site
│   │       ├── contact.php
│   │       ├── error.php
│   │       ├── index.php
│   │       ├── login.php
│   │       └── pages
│   │           └── about.php
│   ├── yiic
│   ├── yiic.bat
│   └── yiic.php
└── themes
    └── classic
        └── views
            ├── layouts
            ├── site
            └── system

通过浏览器查看一下

具体功能后面讲。这里直接讲命令的使用。

2.php yiic messag

php yiic help message打印message命令的相关用法

/* 
USAGE 
 yiic message <config-file> 
DESCRIPTION 
 This command searches for messages to be translated in the specified 
 source files and compiles them into PHP arrays as message source. 
PARAMETERS 
 * config-file: required, the path of the configuration file. You can find 
  an example in framework/messages/config.php. 
  The file can be placed anywhere and must be a valid PHP script which 
  returns an array of name-value pairs. Each name-value pair represents 
  a configuration option. 
  The following options are available: 
  - sourcePath: string, root directory of all source files. 
  - messagePath: string, root directory containing message translations. 
  - languages: array, list of language codes that the extracted messages 
   should be translated to. For example, array('zh_cn','en_au'). 
  - fileTypes: array, a list of file extensions (e.g. 'php', 'xml'). 
   Only the files whose extension name can be found in this list 
   will be processed. If empty, all files will be processed. 
  - exclude: array, a list of directory and file exclusions. Each 
   exclusion can be either a name or a path. If a file or directory name 
   or path matches the exclusion, it will not be copied. For example, 
   an exclusion of '.svn' will exclude all files and directories whose 
   name is '.svn'. And an exclusion of '/a/b' will exclude file or 
   directory 'sourcePath/a/b'. 
  - translator: the name of the function for translating messages. 
   Defaults to 'Yii::t'. This is used as a mark to find messages to be 
   translated. 
  - overwrite: if message file must be overwritten with the merged messages. 
*/ 

主要用于webapp的国际化。

例如将上面生产的testwebap的

登录页面的Username和Password   翻译成中文

上面说需要配置文件。yii为我们提供了配置文件的模板。

framework/messages/config.php

复制frameworkmessagesconfig.php 文件到 protectedmessages下

具体内容修改如下:

dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 
  'messagePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'messages', 
  'languages'=>array('zh_cn'), 
  'fileTypes'=>array('php'), 
  'overwrite'=>true, 
  'exclude'=>array( 
    '.svn', 
    'yiilite.php', 
    'yiit.php', 
    '/i18n/data', 
    '/messages', 
    '/vendors', 
    '/web/js', 
  ), 
); 

/www/yii_dev/testwebap/protected/views/site/login.php

修改如下

labelEx($model,Yii::t('login_message','username')); ?>
textField($model,'username'); ?>
error($model,'username'); ?>
labelEx($model,Yii::t('login_message','password')); ?>
passwordField($model,'password'); ?>
error($model,'password'); ?>

执行如下命令

testwebap/protected/messages
/www/yii_dev/yii/framework# php yiic message "../../testwebap/protected/messages/config.php"
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/components/Controller.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/components/UserIdentity.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/config/console.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/config/main.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/config/test.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/controllers/SiteController.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/models/ContactForm.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/models/LoginForm.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/tests/WebTestCase.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/tests/bootstrap.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/tests/functional/SiteTest.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/layouts/column1.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/layouts/column2.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/layouts/main.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/site/contact.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/site/error.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/site/index.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/site/login.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/views/site/pages/about.php...
Extracting messages from /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/yiic.php...
Saving messages to /home/coder/adata/liuyuqiang/wamp/www/yii_dev/testwebap/protected/messages/../messages/zh_cn/login_message.php...saved.

目录下生成如下文件

/www/yii_dev/testwebap/protected/messages/zh_cn/login_message.php

return array (
'password' => '',
'username' => '',
);

改为

return array (
'password' => '密码',
'username' => '用户名',
);

修改

如下配置文件

/www/yii_dev/testwebap/protected/config/main.php

添加如下

// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster@example.com',
),
'language'=>'zh_cn',
'sourceLanguage'=>'en_us',
);

访问一一下

可以看到翻译成中文了。

可以有乱码的问题,注意编码问题。文件,浏览器要设置统一

更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

您可能感兴趣的文章:

  • yii2框架中使用下拉菜单的自动搜索yii-widget-select2实例分析
  • Yii中创建自己的Widget实例
  • yii中widget的用法
  • PHP的Yii框架中创建视图和渲染视图的方法详解
  • YII Framework框架使用YIIC快速创建YII应用之migrate用法实例详解
  • Yii中Model(模型)的创建及使用方法
  • yii实现创建验证码实例解析
  • yii框架通过控制台命令创建定时任务示例
  • yii框架源码分析之创建controller代码
  • yii2.0实现创建简单widgets示例

本文由星彩网app下载发布于计算机编程,转载请注明出处:2测试工作,注意事项

TAG标签: 星彩网app下载
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。