You are on page 1of 134

http://yiiframework.

ru/doc/guide/ru/index

Yii

Yii
Yii.

, Konstantin Mirin (programmersnotes.info)


, Sam Dark (rmcreative.ru)
, Caveman (caveman.ru)
, xenon
multif
, cr0t (summercode.ru)
, Bethrezen (bethrezen.ru)
20082010, Yii Software LLC.


, Yii.

1.1.5

1.1.4

1.1.3

1.1.2

- Gii

1.1.1

CActiveForm,
, .
, yiic. -
, ,
,
CActiveForm.
.

1.1.0

.
.
.
:
o .
AR ,
SQL .
AR.
.
Zii.
AR 't'.

1.0.11

URL :
o

1.0.10

CPhpMessageSource. :

Yii

o
:
o

1.0.8

:
o
ext , :
o

1.0.7

:
o
AR index,
:
o

1.0.6

update delete:
o
with
:
o
SQL-:
o SQL-
:
o
URL- urlFormat
caseSensitive:
o URL
:
o

1.0.5

Active Record :
o
o
o
Active Record
:
o
CUrlManager URL-:
o

1.0 1.1
,

safeAttributes(). , ,
, rules() .
validate(), beforeValidate(), afterValidate(). setAttributes(), getSafeAttributeNames()
'scenario' .
CModel::scenario.
getValidators() getValidatorsForAttribute(). CModel::getValidators()
, ,
(CModel::scenario).
isAttributeRequired() CModel::getValidatorsForAttribute().
. .
CHtml::scenario. CHtml , .

, '' Active Record

, '' ,
JOIN.

Yii
LIMIT OFFSET, , SQL-,
. , 1.0.x, N+1 SQL, '' N HAS_MANY MANY_MANY.

, Active Record

,
. , 1.0.x, Yii
, ??.
.
AR t. 1.0.x,
. AR
, .
't.'.

, ()

[$i] .
[$i],
(, [$i][$index]).

CActiveRecord. ( ) .

Yii
Yii PHP-
-.
-. Yii ( Yee
[ji:]) (easy), (efficient) (extensible).

-, Yii, - PHP
5.1.0 .
, Yii, (OO), Yii -
.

Yii ?
Yii - ,
-.
, Yii ,
, , (CMS), .

Yii
PHP-, Yii MVC-.
Yii ,
. Yii
-. Yii , .
-, - .

Yii, , :
1. Yii Framework yiiframework.com;
2. Yii , .
: , Yii ,
. PHP-, Yii,
, .

Yii
Yii , -
Yii. , , :
http://hostname/path/to/yii/requirements/index.php
Yii - PHP 5.1.0 . Yii
Apache HTTP server Windows Linux. ,
- PHP 5.


, .
yiic( ), Gii ( ).
, YiiRoot , Yii, WebRoot
-.
yiic :
% YiiRoot/framework/yiic webapp WebRoot/testdrive

: yiic Mac OS, Linux Unix


yiic, .
:
% cd WebRoot
% php YiiRoot/framework/yiic.php webapp testdrive

WebRoot/testdrive .
,
. ,
Yii-, URL:
http://hostname/testdrive/index.php
: , ,
. ,

(. ).

Yii

Yii

Yii

Yii

.
.
testdrive/
index.php

index-test.php

assets/

css/

CSS-

images/

themes/

protected/

yiic

yiic

yiic.bat

yiic Windows

yiic.php

PHP- yiic

commands/

'yiic'

shell/
components/

'yiic shell'

Controller.php

UserIdentity.php

'UserIdentity'

config/

console.php

main.php

test.php

controllers/

Yii

SiteController.php
data/

schema.mysql.sql

MySQL

schema.sqlite.sql

SQLite

testdrive.db

SQLite

extensions/

messages/

models/

LoginForm.php

'login'

ContactForm.php

'contact'

runtime/

tests/

views/

(layout)
layouts/

main.php

column1.php

column2.php

site/

'site'

pages/
about.php

contact.php

'contact'

error.php

'error' (

index.php

'index'

login.php

'login'


- , .
, .
WebRoot/testdrive/protected/config/main.php. , :
return array(

'components'=>array(

'db'=>array(
'connectionString'=>'sqlite:protected/data/testdrive.db',
),
),

);
, SQLite
WebRoot/testdrive/protected/data/testdrive.db . ,
SQLite .
tbl_user:
CREATE TABLE tbl_user (

10

Yii

id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,


username VARCHAR(128) NOT NULL,
password VARCHAR(128) NOT NULL,
email VARCHAR(128) NOT NULL
);
MySQL,
WebRoot/testdrive/protected/data/schema.mysql.sql .
: Yii PHP PDO
PDO. php_pdo php_pdo_sqlite.

CRUD
. CRUD (, ,
) tbl_user
. - Gii.
: Gii 1.1.2.
yiic. yiic CRUD yiic shell.

Gii
, Gii,
WebRoot/testdrive/protected/config/main.php:
return array(

'import'=>array(
'application.models.*',
'application.components.*',
),
'modules'=>array(
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>' ',
),
),
);
URL http://hostname/testdrive/index.php?r=gii
.

User
Model Generator:

11

Yii
Model Generator

Table Name tbl_user. Model Class User. Preview.


, . Generate
protected/models User.php. ,
User tbl_user .

CRUD
, CRUD.
Crud Generator:
CRUD Generator

Model Class User. Controller ID user ( ).


Preview Generate. CRUD .

CRUD
, URL:

12

Yii

http://hostname/testdrive/index.php?r=user
tbl_user. ,
. Create User , ,
. .
Create. ,
.
, .
. ,

. (admin/admin),
:
http://hostname/testdrive/index.php?r=user/admin
. ,
. ,
. ,
.
!

13

Yii

14

Yii

-- (MVC)
Yii -- (MVC, Model-View-Controller),
-.
MVC - ,
. MVC
-,
(, , ),
.
, Yii -, (application),
.
.
Yii:
Yii

Yii

:
Yii

15

Yii
1. URL
http://www.example.com/index.php?r=post/show&id=1, - ,
index.php;
2. ;
3.
request;
4.
urlManager. post,
PostController, show, ;
5.
. show actionShow
. (, access control, benchmarking),
, , , ;
6. Post ID 1;
7. show Post;
8. Post;
9. ;
10. ;
11. .


PHP-, .
PHP-,
.
Yii :
//
defined('YII_DEBUG') or define('YII_DEBUG',true);
// Yii
require_once('path/to/yii/framework/yii.php');
//
$configFile='path/to/config/file.php';
Yii::createWebApplication($configFile)->run();
yii.php,
.


(debug) (production)
YII_DEBUG.
false, .
true yii.php.
- . ,
, ..
.

(application) .
(request resolving)
.
(application-level configuration).
-.
(singleton).
Yii::app().


16

Yii
, CWebApplication,
( ).
.
CWebApplication.
-,
, - . ,
name defaultController:
array(
'name'=>'Yii Framework',
'defaultController'=>'site',
)
PHP- (, protected/config/main.php).
:
return array();
,
Yii::createWebApplication(), .
:
$app=Yii::createWebApplication($configFile);

: , ,
. , ,
, include(), -
.


,
PHP- . , protected
, . basePath
.
. -
Apache HTTP server, .htaccess
:
deny from all



. ,
. , ,
CUrlManager CHttpRequest.
components, ,
. , CMemCache ,
memcache- :
array(

'components'=>array(

'cache'=>array(

17

Yii

'class'=>'CMemCache',
'servers'=>array(
array('host'=>'server1', 'port'=>11211, 'weight'=>60),
array('host'=>'server2', 'port'=>11211, 'weight'=>40),
),
),
),
)
cache components. cache ,
CMemCache, servers.
Yii::app()->ComponentID, ComponentID
(, Yii::app()->cache).
enabled
false. null.
: , . ,
, ,
. ,
.
(, CLogRouter)
, ,
preload.


Yii , ,
-. , request
, URL cookies.
, Yii .
, CWebApplication:
assetManager: CAssetManager (asset files);
authManager: CAuthManager (RBAC);
cache: CCache ; ,
(, CMemCache, CDbCache),
null;
clientScript: CClientScript (javascripts CSS);
coreMessages: CPhpMessageSource Yii;
db: CDbConnection ; ,
connectionString;
errorHandler: CErrorHandler PHP;
format: CFormatter - .
1.1.0;
messages: CPhpMessageSource , Yii;
request: CHttpRequest , ;
securityManager: CSecurityManager ,
(, , );
session: CHttpSession , ;
statePersister: CStatePersister ;
urlManager: CUrlManager URL;
user: CWebUser ;
themeManager: CThemeManager .

18

Yii
CApplication::preinit().
.
.
.
CApplication::init():
o ;
o ;
6. onBeginRequest.
7. :
o ;
o ;
o ;
8. onEndRequest.
1.
2.
3.
4.
5.

(controller) CController .
, .
,
. ,
action.
, ,
. index.
CController::defaultAction.
.
, .
class SiteController extends CController
{
}

.
path/to/xyz,
protected/controllers/path/to/XyzController.php, xyz
(, post protected/controllers/PostController.php).
action. ,
actionEdit, edit.
: 1.0.3 path.to.xyz
path/to/xyz.
(route).
, . ,
post/edit edit PostController , , URL
http://hostname/index.php?r=post/edit .
: . 1.0.1
CUrlManager::caseSensitive false.
, ,
, controller map action map
.


, CWebApplication .
,
:

19

Yii

CWebApplication::catchAllRequest,
, , , .
,
;
CWebApplication::controllerMap,
;
'path/to/xyz',
XyzController,
protected/controllers/path/to/XyzController.php. ,
admin/user UserController
protected/controllers/admin/UserController.php.
, CHttpException 404.
(, 1.0.3),
. , ,
. , ,
.

, , action.

. .
:
class UpdateAction extends CAction
{
public function run()
{
//
}
}
, actions()
:
class PostController extends CController
{
public function actions()
{
return array(
'edit'=>'application.controllers.post.UpdateAction',
);
}
}

application.controllers.post.UpdateAction
protected/controllers/post/UpdateAction.php. , ,
. ,
:
protected/
controllers/
PostController.php
UserController.php
post/

20

Yii

CreateAction.php
ReadAction.php
UpdateAction.php
user/
CreateAction.php
ListAction.php
ProfileAction.php
UpdateAction.php


1.1.4, Yii
. ,
$_GET.
, , ,
create PostController. :
category: ID , . ;
language: , , .
$_GET
:
class PostController extends CController
{
public function actionCreate()
{
if(isset($_GET['category']))
$category=(int)$_GET['category'];
else
throw new CHttpException(404,' ');
if(isset($_GET['language']))
$language=$_GET['language'];
else
$language='en';
//
}
}
, , :
class PostController extends CController
{
public function actionCreate($category, $language='en')
{
$category=(int)$category;
//

21

Yii

}
}

actionCreate.
$_GET. $language en, ,
. $category ,

CHttpException ( 400).
1.1.5, Yii .
:
class PostController extends CController
{
public function actionCreate(array $categories)
{
// Yii $categories
}
}
array $categories. ,
$_GET['categories'] , ,
.
: array, (..
). $_GET- HTTP.

(filter) ,
. , ,
, . ,
, ,
.
. ,
,
.
. filter.
, filterAccessControl ,
accessControl. :
public function filterAccessControl($filterChain)
{
//
$filterChain->run()
}
$filterChain CFilterChain, ,
. $filterChain->run()
, .
CFilter .
:
class PerformanceFilter extends CFilter

22

Yii

{
protected function preFilter($filterChain)
{
// ,
return true; // false ,
}
protected function postFilter($filterChain)
{
// ,
}
}
, ,
CController::filters(), . :
class PostController extends CController
{

public function filters()


{
return array(
'postOnly + edit, create',
array(
'application.filters.PerformanceFilter - edit, create',
'unit'=>'second',
),
);
}
}
: postOnly PerformanceFilter. postOnly
( CController), PerformanceFilter
. application.filters.PerformanceFilter
protected/filters/PerformanceFilter. PerformanceFilter
, .
unit PerformanceFilter 'second'.
'+' '-' ,
. postOnly edit create,
PerformanceFilter , edit create. '+' '-' ,
.

(model) CModel .
-.
.
. .
, .

23

Yii
Yii : (form model) Active Record.
CModel.
CFormModel. ,
. , , , .
,
.
.
Active Record (AR) ,
- . AR
CActiveRecord , .
AR-. AR-
Active Record.

PHP-,
. PHP, ,
.
, ,
. , ,
.
. ,
edit edit.php.
CController::render(), .
protected/views/ControllerID.
$this. ,
: $this->propertyName.
, :
$this->render('edit', array(
'var1'=>$value1,
'var2'=>$value2,
));
render() . ,
$var1 $var2.

(layout) .
, . ,
,
.

<?php echo $content; ?>

$content .
render(). ,
protected/views/layouts/main.php.
CWebApplication::layout CController::layout.
renderPartial().

(widget)- CWidget . ,
.
. ,
.
.
:

24

Yii

<?php $this->beginWidget('path.to.WidgetClass'); ?>


,
<?php $this->endWidget(); ?>

<?php $this->widget('path.to.WidgetClass'); ?>


.
, ,
CBaseController::beginWidget CBaseController::widget. ,
CMaskedTextField ,
, , ,
:
<?php
$this->widget('CMaskedTextField',array(
'mask'=>'99/99/9999'
));
?>
CWidget init() run():
class MyWidget extends CWidget
{
public function init()
{
// CController::beginWidget()
}
public function run()
{
// CController::endWidget()
}
}
, . ,
views , .
CWidget::render(), ,
. ,
. , $this , .


, Yii
. , ,
Yii , .
.
. errorXXX
, CHttpException XXX. ,
CHttpException 404,
error404.
Yii , framework/views.

protected/views/system.

25

Yii

Yii- , .
(component) CComponent .
, .
CComponent , .


- (public member variable).
. :
$width=$component->textWidth; // textWidth
$component->enableCaching=true; // enableCaching
,
. , (getter)
(setter) , :
public function getTextWidth()
{
return $this->_textWidth;
}
public function setTextWidth($value)
{
$this->_textWidth=$value;
}
textWidth ( ),
.
getTextWidth(), .
, setTextWidth().
, , .
:
( ,
.).
:
. , .


,
( ). ,
.
.
, on.
, , .
onClicked:
public function onClicked($event)
{
$this->raiseEvent('onClicked', $event);

26

Yii

}
$event CEvent ,
. , :
$component->onClicked=$callback;
$callback callback- PHP (. PHP- call_user_func).
, . :
array($object,'methodName').
:
function methodName($event)
{

}
$event , ( raiseEvent()).
$event CEvent . ,
, .
1.0.10 ,
PHP 5.3+. ,
$component->onClicked=function($event) {

}
onClicked(), onClicked ( onClicked()),
.
.
, .
, $event->handled true.


1.0.2, (mixin)
. ,
, ,
( ).
.
IBehavior.
CBehavior. ,
, CModelBehavior CActiveRecordBehavior,
, .
,
attach(). :
// $name
$component->attachBehavior($name,$behavior);
// test() $behavior
$component->test();
, . ,
tree ,
:

27

Yii

$behavior=$component->tree;
// :
// $behavior=$component->asa('tree');
,
. :
$component->disableBehavior($name);
//
$component->test();
$component->enableBehavior($name);
//
$component->test();
, , ,
, , .
. ,
, .
, .
1.1.0, ,
. , /
. , xyz $a.
$a->xyz .

: , 1.0.3.
, , ,
. .
, .
,
.
. ,
, . ,
, , , .,
,
.


,
. .
forum:
forum/
ForumModule.php

components/

views/
controllers/
DefaultController.php

extensions/

models/

28

Yii

views/

layouts/

default/

index.php

'index'

, CWebModule.
ucfirst($id).'Module', $id
( ).
. , CWebModule::params
, CWebModule::components
.
: ,
Gii.


modules
.
modules. , forum, ,
:
return array(

'modules'=>array('forum',),

);
, .
. , forum
postPerPage, :
return array(

'modules'=>array(
'forum'=>array(
'postPerPage'=>20,
),
),

);
module
.
. , , postPerPage,
:
$postPerPage=Yii::app()->controller->module->postPerPage;
// , $this
// $postPerPage=$this->module->postPerPage;

29

Yii
,
moduleID/controllerID/actionID. , , forum
PostController, forum/post/create
, create . URL,
, : http://www.example.com/index.php?r=forum/post/create.
: controllers,
, . , , PostController
forum/controllers/admin, create
forum/admin/post/create.


, ..
, . -,
-. - modules -
, .

parentModuleID/childModuleID/controllerID/actionID.


Yii. .
,
:
RootAlias.path.to.target
RootAlias .
YiiBase::getPathOfAlias() .
, system.web.CController yii/framework/web/CController.
YiiBase::setPathOfAlias() .


, :
system: ;
zii: Zii;
application: ;
webroot: , . ,
1.0.3.
ext: , . ,
1.0.8.
, , ,
. ,
1.0.3.

Importing Classes
, . ,
CController :
Yii::import('system.web.CController');
import , include require,
(
PHP).
, include_once require_once.
: ,
. Yii .

30

Yii


1.1.5, Yii
, .
.
, Yii.
, CWebApplication::run():
Yii::$classMap=array(
'ClassName1' => 'path/to/ClassName1.php',
'ClassName2' => 'path/to/ClassName2.php',
......
);


, ,
, , .
Yii::import('system.web.*');
import, , .
, Yii::createComponent()
, .


,
, . .
.
.
: PHP 5.3.0 ,
, .
Yii- 'C' ( 'class'),
. ,
'C' Yii-.


, . ,
applicationcomponentsGoogleMap applicationcomponents.
PHP 5.3.0 .
1.1.5
. ,
applicationcomponentsGoogleMap .
Yii.
, ,
, . , applicationcomponentsGoogleMap
, application.components.GoogleMap.

Yii . ,
. ,
Yii .
, Yii. ,
WebRoot , .

URL
, Yii URL :

31

Yii

http://hostname/index.php?r=ControllerID/ActionID
GET- r , Yii
. ActionID ,
( CController::defaultAction). ControllerID (
r ), (
CWebApplication::defaultController).
CUrlManager SEO- URL,
http://hostname/ControllerID/ActionID.html.
URL.

Yii , , ,
.
,
(, $basePath, runController(), LinkPager). private
(, $_actionList).
PHP 5.3.0, ,
.
"C".
Controller.

Controller. , PageController page.
. URL ( ,
/index.php?r=page/index /index.php?r=PageController/index).

-,
, . ,
array('name'=>'My application', 'basePath'=>'./protected') name
basePath .
, , .
, .
,
.

.
, , . , CController
CController.php. ,
. .
(, )
.
, . ,
index index.php. PHP-,
HTML PHP-, .
. PHP, ,
.

Yii .
.
WebRoot/protected: ,
PHP- .
application.
. CWebApplication::basePath;
WebRoot/protected/runtime: ,
.
. CApplication::runtimePath;

32

Yii

WebRoot/protected/extensions: .
CApplication::extensionPath;
WebRoot/protected/modules: ,
.
CWebApplication::modulePath;
WebRoot/protected/controllers: .
CWebApplication::controllerPath;
WebRoot/protected/views: ,
, .
CWebApplication::viewPath;
WebRoot/protected/views/ControllerID:
. ControllerID .
CController::viewPath;
WebRoot/protected/views/layouts: .
CWebApplication::layoutPath;
WebRoot/protected/views/system:
( ).
CWebApplication::systemViewPath;
WebRoot/assets: ( ,
).
-. CAssetManager::basePath;
WebRoot/themes: ,
. ,
. CThemeManager::basePath.


. .
, Yii .
.
(, product_order).
, , .
.
. , tbl_.
, .


Yii, -
. , , ,
.
1. . yiic, c
, , ;
2. .
(,
);
3. .
active record Gii,
;
4. .
. ,
, .
Gii ;
5. . ;
6. ;
7. ;
8. , ;
9. ,
.
10. .
.

33

Yii



, HTML , ,
.
. , ,
, .
, ,
. , , , ;
, Active Record.
CModel,
.
: . ,
Active Record.


LoginForm, ,
.
, LoginForm
.
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe=false;
}
LoginForm : $username, $password $rememberMe.
, , .
$rememberMe false,
.
: , ,
- , . ,
, , , .


, , ,
, , , .
.
rules(), .
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe=false;
private $_identity;

34

Yii

public function rules()


{
return array(
array('username, password', 'required'),
array('rememberMe', 'boolean'),
array('password', 'authenticate'),
);
}
public function authenticate($attribute,$params)
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password',' .');
}
}
, , username password ,
password .
rememberMe true false.
, rules(), :
array('AttributeList', 'Validator', 'on'=>'ScenarioList', )
AttributeList , ,
; Validator ; on
, , ;
-,
.
Validator . -, Validator
, authenticate .
:
/**
* @param string the name of the attribute to be validated
* @param array options specified in the validation rule
*/
public function ValidatorName($attribute,$params) { }
Validator .
.
.
CValidator.
. , required
CRequiredValidator, ,
. ,
Yii:
boolean: CBooleanValidator, ,
CBooleanValidator::trueValue CBooleanValidator::falseValue;

35

Yii

captcha: CCaptchaValidator, ,
;
compare: CCompareValidator, ,
;
email: CEmailValidator, email ;
default: CDefaultValueValidator,
;
exist: CExistValidator,
;
file: CFileValidator,
;
filter: CFilterValidator,
;
in: CRangeValidator, ,
;
length: CStringValidator,
;
match: CRegularExpressionValidator,
;
numerical: CNumberValidator, ,
;
required: CRequiredValidator, ,
;
type: CTypeValidator,
;
unique: CUniqueValidator, ,
;
url: CUrlValidator, URL.
:
//
array('username', 'required'),
// 3 12
array('username', 'length', 'min'=>3, 'max'=>12),
// password password2
array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
// `password`

array('password', 'authenticate', 'on'=>'login'),


, , ,
. , :
$model=new LoginForm;
if(isset($_POST['LoginForm']))
$model->attributes=$_POST['LoginForm'];
,
$_POST['LoginForm'] .
:
foreach($_POST['LoginForm'] as $name=>$value)
{

36

Yii

if($name )
$model->$name=$value;
}
, . ,
, , ,
, , .
1.0 1.1.
.

1.1
1.1 , ,
. ,
array('username, password', 'required', 'on'=>'login, register'),
array('email', 'required', 'on'=>'register'),
username password login, username,
password email register. ,
login, username password , ..
login. ,
register, .
//
$model=new User('login');
if(isset($_POST['User']))
$model->attributes=$_POST['User'];
//
$model=new User('register');
if(isset($_POST['User']))
$model->attributes=$_POST['User'];
,
? , -
?
, ,
, (,
). , ,
.
.
,
. safe:
array('content', 'safe')
, unsafe,
:
array('permission', 'unsafe')
unsafe
.

1.0
37

Yii
1.0 safeAttributes
. -
CFormModel , , CActiveRecord.
,
. , , ,
, username password.
:
public function safeAttributes()
{
return array(
parent::safeAttributes(),
'login' => 'username, password',
);
}
, , safeAttributes :
array(
// * * ,
//
'attr1, attr2, ',
*
// * * 'scenario1'
'scenario1' => 'attr2, attr3, ',
*
// 'scenario2'
'scenario2' => 'attr1, attr3, ',
)
(..
),
:
'attr1, attr2, '
, ,
, :
$model->permission='admin';
$model->id=1;


, CModel::validate(),
.
. CActiveRecord
CActiveRecord::save().
scenario , , ,
.
. scenario ,
. ,
login, username password.

38

Yii
register : email, address .
, register:
// User `register`.
:
// $model=new User;
// $model->scenario='register';
$model=new User('register');
//
$model->attributes=$_POST['User'];
//
if($model->validate())

//

else

on . on ,
. ,
public function rules()
{
return array(
array('username, password', 'required'),
array('password_repeat', 'required', 'on'=>'register'),
array('password', 'compare', 'on'=>'register'),
);
}
,
register.


.
CModel::getErrors() CModel::getError().
, .
, - ,
CModel::hasErrors(). ,
CModel::getErrors(). , .


.
, . , ,
, , , .
CModel . ,
attributeLabels().
,
.


. form, action
URL login, .

39

Yii
, LoginForm.
. HTML .
Yii (helper).
, , CHtml::textField(),
CHtml::dropDownList().
: , ,
, HTML ? :
. , , , ,
, .
CHtml::textField($name,$value,array('submit'=>''));
, JavaScript.
CHtml.
$model LoginForm:
<div class="form">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($model); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'username'); ?>
<?php echo CHtml::activeTextField($model,'username'); ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'password'); ?>
<?php echo CHtml::activePasswordField($model,'password'); ?>
</div>
<div class="row rememberMe">
<?php echo CHtml::activeCheckBox($model,'rememberMe'); ?>
<?php echo CHtml::activeLabel($model,'rememberMe'); ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton(''); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
, , . , CHtml::activeLabel()
, , ,
CSS error, CSS .
CHtml::activeTextField()
.
CSS form.css, yiic,
:

40

Yii

1.1.1, CActiveForm,
, . CActiveForm
:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm'); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->label($model,'username'); ?>
<?php echo $form->textField($model,'username') ?>
</div>
<div class="row">
<?php echo $form->label($model,'password'); ?>
<?php echo $form->passwordField($model,'password') ?>
</div>
<div class="row rememberMe">
<?php echo $form->checkBox($model,'rememberMe'); ?>
<?php echo $form->label($model,'rememberMe'); ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton(''); ?>
</div>

41

Yii

<?php $this->endWidget(); ?>


</div><!-- form -->


HTML ,
. ,
. ,
, , Yii
1.1.0.


CForm , HTML
, , , .
CForm,
.
. CForm.
, : CForm::buttons
CForm::elements. ( ), ,
CForm, CForm::elements
. CForm::buttons
CForm::elements.
, , ,
, . CForm ,
.


, .
login:
public function actionLogin()
{
$model = new LoginForm;
$form = new CForm('application.views.site.loginForm', $model);
if($form->submitted('login') && $form->validate())
$this->redirect(array('site/index'));
else
$this->render('login', array('form'=>$form));
}
, CForm, , ,
application.views.site.loginForm. CForm,
, LoginForm.
,
site/index. , login, .
application.views.site.loginForm PHP
protected/views/site/loginForm.php. , ,
CForm:
return array(
'title'=>', ',

'elements'=>array(

42

Yii

'username'=>array(
'type'=>'text',
'maxlength'=>32,
),
'password'=>array(
'type'=>'password',
'maxlength'=>32,
),
'rememberMe'=>array(
'type'=>'checkbox',
)
),
'buttons'=>array(
'login'=>array(
'type'=>'submit',
'label'=>'',
),
),
);
, , -,
CForm. ,
, CForm::elements CForm::buttons. ,
.
.
login:
<h1></h1>
<div class="form">
<?php echo $form; ?>
</div>

: echo $form; echo $form->render();.


CForm
__toString, render(), .


, , ,
. , CForm::elements.
CForm::buttons
CForm::elements.
CForm::elements , .
, .


, , , ,
.
CFormInputElement. CForm::elements :

43

Yii

'username'=>array(
'type'=>'text',
'maxlength'=>32,
),
, username, text maxlength
32.
CFormInputElement
. , hint , items,
checkbox radio.
CFormInputElement, HTML- input.
, maxlength CFormInputElement,
maxlength HTML- input.
[CFormInputElement].

type. . , text
, input, password .
CFormInputElement :
text
hidden
password
textarea
file
radio
checkbox
listbox
dropdownlist
checkboxlist
radiolist
"" dropdownlist, checkboxlist radiolist.
items input. :
'gender'=>array(
'type'=>'dropdownlist',
'items'=>User::model()->getGenderOptions(),
'prompt'=>' :',
),

class User extends CActiveRecord


{
public function getGenderOptions()
{
return array(
0 => '',
1 => '',
);
}

44

Yii

}
:
, getGenderOptions User.
, type .
CInputWidget CJuiInputWidget. ,
. ,
.


, , HTML .
, ,
. HTML CForm::elements
. CForm::elements
. :
return array(
'elements'=>array(
......
'password'=>array(
'type'=>'password',
'maxlength'=>32,
),
'<hr />',
'rememberMe'=>array(
'type'=>'checkbox',
)
),
......
);
password rememberMe.
,
. ,
, .


.
, :
. , ,
. ,
( ),
. ,
.
, , CForm. ,
, form CForm::elements:
return array(
'elements'=>array(
......
'user'=>array(
'type'=>'form',

45

Yii

'title'=>' ',
'elements'=>array(
'username'=>array(
'type'=>'text',
),
'password'=>array(
'type'=>'password',
),
'email'=>array(
'type'=>'text',
),
),
),
'profile'=>array(
'type'=>'form',
......
),
......
),
......
);
, , CForm::elements.
,
CForm::model.
, CForm. ,
, CForm .
form,
, . , , XyzForm (,
Form), XyzForm.


, . CForm::elements
CFormElementCollection, CMap
. , , username
login , :
$username = $form->elements['username'];
email , :
$email = $form->elements['user']->elements['email'];
CForm CForm::elements , :
$username = $form['username'];
$email = $form['user']['email'];


.
.

46

Yii
, .
User, Profile.
register :
public function actionRegister()
{
$form = new CForm('application.views.user.registerForm');
$form['user']->model = new User;
$form['profile']->model = new Profile;
if($form->submitted('register') && $form->validate())
{
$user = $form['user']->model;
$profile = $form['profile']->model;
if($user->save(false))
{
$profile->userID = $user->id;
$profile->save(false);
$this->redirect(array('site/index'));
}
}
$this->render('register', array('form'=>$form));
}
, application.views.user.registerForm.
,
. model
. , $user->save(false) false,
. .
protected/views/user/registerForm.php:
return array(
'elements'=>array(
'user'=>array(
'type'=>'form',
'title'=>' ',
'elements'=>array(
'username'=>array(
'type'=>'text',
),
'password'=>array(
'type'=>'password',
),
'email'=>array(
'type'=>'text',
)
),
),

47

Yii

'profile'=>array(
'type'=>'form',
'title'=>'',
'elements'=>array(
'firstName'=>array(
'type'=>'text',
),
'lastName'=>array(
'type'=>'text',
),
),
),
),
'buttons'=>array(
'register'=>array(
'type'=>'submit',
'label'=>'',
),
),
);
, CForm::title. ,
HTML- fieldset .
register:
<h1></h1>
<div class="form">
<?php echo $form; ?>
</div>


(
) ( CForm::render). ,
CForm::render, .
.
CForm::render, , , CForm::elements
CForm::buttons CFormElement::render . :
class MyForm extends CForm
{
public function render()
{
$output = $this->renderBegin();

48

Yii

foreach($this->getElements() as $element)
$output .= $element->render();
$output .= $this->renderEnd();
return $output;
}
}
_form:
<?php
echo $form->renderBegin();
foreach($form->getElements() as $element)
echo $element->render();
echo $form->renderEnd();
:
<div class="form">
$this->renderPartial('_form', array('form'=>$form));
</div>
( ,
), :
-
<?php echo $form['username']; ?>
-
<?php echo $form['password']; ?>
-

. , . , ,
, .


(DAO)
(DAO) API ,
.
, DAO .
Yii DAO PHP Data Objects (PDO) - ,
, , MySQL, PostgreSQL.

49

Yii
Yii DAO , PDO PDO,
(, PDO_MYSQL).
Yii DAO :
CDbConnection: ;
CDbCommand: SQL ;
CDbDataReader: ,
SQL-;
CDbTransaction: .
Yii DAO.


CDbConnection
. , (, ,
, .), DSN.
, (, DSN /).
$connection=new CDbConnection($dsn,$username,$password);
// . trycatch
$connection->active=true;

$connection->active=false;

// close connection

DSN PDO. , DSN PDO,


, ,
.
PDO. DSN:
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
CDbConnection CApplicationComponent,
. db
:
array(

'components'=>array(

'db'=>array(
'class'=>'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=testdb',
'username'=>'root',
'password'=>'password',
'emulatePrepare'=>true,

// MySQL

),
),
)
Yii::app()->db.
, CDbConnection::autoConnect false.
.

SQL-
50

Yii
, SQL-, CDbCommand.
CDbCommand CDbConnection::createCommand() SQL:
$connection=Yii::app()->db; // ,
"db"
// :
// $connection=new CDbConnection($dsn,$username,$password);
$command=$connection->createCommand($sql);
// , SQL- :
// $command->text=$newSQL;
SQL- CDbCommand:
execute(): SQL- INSERT, UPDATE DELETE.
, ;
query(): SQL-, , , SELECT.
, CDbDataReader,
. queryXXX(),
.
SQL- , .
$rowCount=$command->execute();

// `INSERT`, `UPDATE` `DELETE`

$dataReader=$command->query();

// `SELECT`

$rows=$command->queryAll();

//

$row=$command->queryRow();

//

$column=$command->queryColumn(); //
$value=$command->queryScalar();

//


, CDbCommand::query() CDbDataReader,
CDbDataReader::read().
CDbDataReader foreach.
$dataReader=$command->query();
// read() false
while(($row=$dataReader->read())!==false) { }
// foreach
foreach($dataReader as $row) { }
//
$rows=$dataReader->readAll();

: queryXXX(), query(), .
, queryRow() .


, , -
, , , .
, CDbTransaction:
;
, ;

51

Yii

, ,
;
- , .
:
$transaction=$connection->beginTransaction();
try
{
$connection->createCommand($sql1)->execute();
$connection->createCommand($sql2)->execute();
// SQL
$transaction->commit();
}
catch(Exception $e) //
{
$transaction->rollBack();
}


SQL-
SQL-, SQL-
(placeholder), .
( )
( ).
CDbCommand::bindParam() CDbCommand::bindValue().
, .. .
SQL-.
// SQL :username :email
$sql="INSERT INTO tbl_user(username, email) VALUES(:username,:email)";
$command=$connection->createCommand($sql);
// :username
$command->bindParam(":username",$username,PDO::PARAM_STR);
// :email
$command->bindParam(":email",$email,PDO::PARAM_STR);
$command->execute();
//
$command->bindParam(":username",$username2,PDO::PARAM_STR);
$command->bindParam(":email",$email2,PDO::PARAM_STR);
$command->execute();
bindParam() bindValue() , ,
PHP, . ,
,
bindParam().
PHP.


PHP.
:
$sql="SELECT username, email FROM tbl_user";

52

Yii

$dataReader=$connection->createCommand($sql)->query();
// (username) $username
$dataReader->bindColumn(1,$username);
// (email) $email
$dataReader->bindColumn(2,$email);
while($dataReader->read()!==false)
{
// $username $email username email
}


1.1.0, Yii .
, .
, ,
. ,
tbl_, yii_.
, CDbConnection::tablePrefix
. , SQL , {{TableName}} ,
TableName . , tbl_user,
tbl_ , :
$sql='SELECT * FROM {{user}}';
$users=$connection->createCommand($sql)->queryAll();

Active Record
Yii DAO , ,
90% SQL-, CRUD (, ,
). , , SQL-,
. Active Record.
Active Record - (ORM).
AR ( ) , AR ,
CRUD AR. , . , ,
tbl_post.
$post=new Post;
$post->title=' ';
$post->content=' ';
$post->save();
, AR CRUD-,
AR .
. , MySQL SQL AUTOINCREMENT AUTO_INCREMENT.
CREATE TABLE tbl_post (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
title VARCHAR(128) NOT NULL,
content TEXT NOT NULL,

53

Yii

create_time INTEGER NOT NULL


);

: AR , .
PHP SQL-.
Yii DAO.


AR . , ,
db CDbConnection,
. :
return array(
'components'=>array(
'db'=>array(
'class'=>'system.db.CDbConnection',
'connectionString'=>'sqlite:path/to/dbfile',
//
// 'schemaCachingDuration'=>3600,
),
),
);

: AR ,
. , ,
CDbConnection::schemaCachingDuration
.
AR :
MySQL 4.1
PostgreSQL 7.3
SQLite 2 3
Microsoft SQL Server 2000
Oracle
: Microsoft SQL Server 1.0.4; Oracle
1.0.5.
db , AR,
, CActiveRecord::getDbConnection(). CActiveRecord
AR.
: AR .
, AR
getDbConnection(). ,
CActiveRecord::db.

AR-
AR
CActiveRecord. AR ,

54

Yii
. , AR,
tbl_post.
class Post extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'tbl_post';
}
}

: AR ,
, AR-. , AR-
protected/models, :
return array(
'import'=>array(
'application.models.*',
),
);

AR- . ,
tableName(). model() AR-.
: , 1.1.0, tableName() AR :
public function tableName()
{
return '{{post}}';
}
, ,
.
AR-.
, title:
$post=new Post;
$post->title=' ';
title Post, , ,
. , title tbl_post

55

Yii
CActiveRecord PHP __get().
, .
:
-. , PostgreSQL
,
, .
.
AR .
, AR ,
. primaryKey():
public function primaryKey()
{
return 'id';
// :
// return array('pk1', 'pk2');
}


,
, , , save()
.
$post=new Post;
$post->title=' ';
$post->content=' ';
$post->create_time=time();
$post->save();
, AR
. , id
.
(,
), AR
. AR-.
class Post extends CActiveRecord
{
public $title=', ';

}
$post=new Post;
echo $post->title;

// : ,

1.0.2, ( )
CDbExpression. , ,
MySQL NOW(), :
$post=new Post;
$post->create_time=new CDbExpression('NOW()');
// $post->create_time='NOW()';

56

Yii

// .. 'NOW()'
$post->save();

: , AR
SQL, , SQL . ,
. , SQL ,
CWebLogRoute . 1.0.5,
CDbConnection::enableParamLogging true .


find:
// ,
$post=Post::model()->find($condition,$params);
//
$post=Post::model()->findByPk($postID,$condition,$params);
//
$post=Post::model()->findByAttributes($attributes,$condition,$params);
// , SQL
$post=Post::model()->findBySql($sql,$params);
find Post::model(). , model()
AR-. AR,
(- ) .
find , ,
Post, .
, , echo $post->title;.
, , , find null.
$condition $params . $condition
, WHERE SQL-, $params
, , $condition. :
// , postID=10
$post=Post::model()->find('postID=:postID', array(':postID'=>10));

: ,
postID . , PostgreSQL,
"postID"=:postID, PostgreSQL
.
, $condition .
$condition CDbCriteria,
WHERE . :
$criteria=new CDbCriteria;
$criteria->select='title';

// 'title'

$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);

57

Yii

$post=Post::model()->find($criteria); // $params
, CDbCriteria, $params
, CDbCriteria, .
CDbCriteria,
, .
:
$post=Post::model()->find(array(
'select'=>'title',
'condition'=>'postID=:postID',
'params'=>array(':postID'=>10),
));

: , ,
findByAttributes(), $attributes
, .
findByNameAndTitle. ,
, .
, , ,
findAll, . , findAll find
.
// ,
$posts=Post::model()->findAll($condition,$params);
//
$posts=Post::model()->findAllByPk($postIDs,$condition,$params);
//
$posts=Post::model()->findAllByAttributes($attributes,$condition,$params);
// , SQL-
$posts=Post::model()->findAllBySql($sql,$params);
find, findAll , , ,
null, .
find findAll , :
// ,
$n=Post::model()->count($condition,$params);
// SQL-
$n=Post::model()->countBySql($sql,$params);
// , ,
$exists=Post::model()->exists($condition,$params);


AR , .
$post=Post::model()->findByPk(10);
$post->title='new post title';
$post->save(); //

58

Yii
, save() .
AR new, save()
. , AR find
findAll, save() . ,
CActiveRecord::isNewRecord , AR .
, .
AR :
// ,
Post::model()->updateAll($attributes,$condition,$params);
// , (
)
Post::model()->updateByPk($pk,$attributes,$condition,$params);
// - ,
Post::model()->updateCounters($counters,$condition,$params);
$attributes , , $counters
, , $condition $params
.


, AR .
$post=Post::model()->findByPk(10); // , ID=10
$post->delete(); //
, AR ,
.
:
// ,
Post::model()->deleteAll($condition,$params);
// , (
)
Post::model()->deleteByPk($pk,$condition,$params);


, ,
. , ,
.
AR save().
, AR- rules(). ,
, .
:
if($post->save())
{
//
}
else
{

59

Yii

// ,
getErrors()
}
, ,
AR. :
$post->title=$_POST['title'];
$post->content=$_POST['content'];
$post->save();
, . ,
attributes .
.
// , $_POST['Post'] ,

$post->attributes=$_POST['Post'];
$post->save();


AR ,
,
, , AR-.
, CActiveRecord::equals().
: AR , Yii AR
. . ,
Yii , primaryKey
AR.


CActiveRecord ,
AR.
beforeValidate afterValidate: ;
beforeSave afterSave: AR;
beforeDelete afterDelete: AR;
afterConstruct: AR,
new;
beforeFind: , finder AR (, find(),
findAll()). 1.0.9.
afterFind: AR,
.

AR
AR dbConnection,
CDbConnection. , ,
Yii DAO:
$model=Post::model();
$transaction=$model->dbConnection->beginTransaction();
try
{
// ,

60

Yii

// , ,
$post=$model->findByPk(10);
$post->title='new post title';
$post->save();
$transaction->commit();
}
catch(Exception $e)
{
$transaction->rollBack();
}


: , 1.0.5.
Ruby on Rails.
,
AR.
CActiveRecord::scopes() -.
Post: published
recently:
class Post extends CActiveRecord
{

public function scopes()


{
return array(
'published'=>array(
'condition'=>'status=1',
),
'recently'=>array(
'order'=>'create_time DESC',
'limit'=>5,
),
);
}
}
,
CDbCriteria. , recently , order create_time DESC, limit
5. , 5 .
find.
. ,
:
$posts=Post::model()->published()->recently()->findAll();

61

Yii
, find.
, ,
find. .
1.0.6, update
delete. , :
Post::model()->published()->recently()->delete();

: . ,
ClassName::model().


. ,
recently. , ,
CActiveRecord::scopes, , :
public function recently($limit=5)
{
$this->getDbCriteria()->mergeWith(array(
'order'=>'create_time DESC',
'limit'=>$limit,
));
return $this;
}
, , 3 ,
:
$posts=Post::model()->published()->recently(3)->findAll();
3, 5 .


,
( ). ,
, . ,
,
. CActiveRecord::defaultScope :
class Content extends CActiveRecord
{
public function defaultScope()
{
return array(
'condition'=>"language='".Yii::app()->language."'",
);
}
}
:
$contents=Content::model()->findAll();

62

Yii
, SELECT .
INSERT, UPDATE DELETE .

Active Record
Active Record (AR) .
, AR
.
AR , -
.
.
,
- (ER).
ER

: . SQLite < 3.6.19


, , , .


, AR , AR, AR-
.
AR-
. , A :
-- (, tbl_user tbl_post), -- (, tbl_user tbl_profile)
-- (, tbl_category tbl_post). AR :
BELONGS_TO: --, (,
Post User);
HAS_MANY: --,
(, User Post);
HAS_ONE: HAS_MANY, (, User
Profile);
MANY_MANY: -- .
--,
-- -. , tbl_post_category.
AR MANY_MANY BELONGS_TO HAS_MANY.
, Post Category, Category Post.

63

Yii
AR, relations() CActiveRecord.
.
:
'VarName'=>array('RelationType', 'ClassName', 'ForeignKey', )
VarName , RelationType ,
ClassName AR-, AR-, ForeignKey
, . ,
, .
, User Post.
class Post extends CActiveRecord
{

public function relations()


{
return array(
'author'=>array(self::BELONGS_TO, 'User', 'author_id'),
'categories'=>array(self::MANY_MANY, 'Category',
'tbl_post_category(post_id, category_id)'),
);
}
}
class User extends CActiveRecord
{

public function relations()


{
return array(
'posts'=>array(self::HAS_MANY, 'Post', 'author_id'),
'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'),
);
}
}

: ,
. MANY_MANY
. , categories Post
tbl_post_category(post_id, category_id).
AR- .
(-)
(-) AR. , $author AR- User,
$author->posts Post.


AR-.
, ,

64

Yii
,
AR. (-) .
, (lazy loading), ..
. :
// ID=10
$post=Post::model()->findByPk(10);
// . .
$author=$post->author;

: ,
null BELONGS_TO HAS_ONE HAS_MANY MANY_MANY.
, HAS_MANY MANY_MANY
, Trying to get property of non-object.
, . ,
N , N
. , (eager loading).
AR
AR. AR with() find
findAll. :
$posts=Post::model()->with('author')->findAll();
Post. , author
User .
,
!
with() .
, :
$posts=Post::model()->with('author','categories')->findAll();
, .
, with() , ,
:
$posts=Post::model()->with(
'author.profile',
'author.posts',
'categories')->findAll();
,
.
1.1.0, CDbCriteria::with:
$criteria=new CDbCriteria;
$criteria->with=array(
'author.profile',
'author.posts',
'categories',
);

65

Yii

$posts=Post::model()->findAll($criteria);

$posts=Post::model()->findAll(array(
'with'=>array(
'author.profile',
'author.posts',
'categories',
)
);


, .
- .
.
select: AR-.
'*', .. .
.
condition: WHERE, .
.
params: SQL-.
-. , 1.0.3;
on: ON. , ,
AND.
. MANY_MANY.
, 1.0.2;
order: ORDER BY, .
.
with: , .
.
joinType: . LEFT OUTER
JOIN;
alias: , .
1.0.1. null, ,
.
together: , ,
, .
HAS_MANY MANY_MANY. false,
HAS_MANY MANY_MANY SQL
, ..
. true,
, ,
. ,
,
.
. , 1.0.3;
join: JOIN. . 1.1.3.
group: GROUP BY, .
.
having: HAVING, .
. ,
1.0.1.
index: , ,
. ,

66

Yii
, .
HAS_MANY MANY_MANY. 1.0.7.
,
:
limit: .
BELONGS_TO;
offset: .
BELONGS_TO.
posts User,
:
class User extends CActiveRecord
{
public function relations()
{
return array(
'posts'=>array(self::HAS_MANY, 'Post', 'author_id',
'order'=>'posts.create_time DESC',
'with'=>'categories'),
'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'),
);
}
}
$author->posts, ,
. .


, .
.
t,.
. , Post
Comment t comments:
$posts=Post::model()->with('comments')->findAll();
, Post Comment create_time,
, ,
, .
create_time :
$posts=Post::model()->with('comments')->findAll(array(
'order'=>'t.create_time, comments.create_time'
));

: 1.1.0.
Yii ,
??. . 1.0.x
.


67

Yii
1.0.2, with(),
with.
relations(). , User, ,
( order
), :
User::model()->with(array(
'posts'=>array('order'=>'posts.create_time ASC'),
'profile',
))->findAll();
1.0.5
. , ,
. , ,
status 1:
$user=User::model()->findByPk(1);
$posts=$user->posts(array('condition'=>'status=1'));


, , ,
.
SQL-. ..
. ,
.
, . ,
10 , SQL-
.
-: , .
SQL . ,
.
? .
SQL
. , SQL ,
.
Yii together,
. Yii , SQL
. together false,
SQL . , ,
, comments Post
:
public function relations()
{
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'post_id', 'together'=>false),
);
}
:
$posts = Post::model()->with(array('comments'=>array('together'=>false)))->findAll();

68

Yii

: 1.0.x N+1 SQL


N HAS_MANY MANY_MANY. HAS_MANY MANY_MANY
. together() with() SQL
:
$posts=Post::model()->with(
'author.profile',
'author.posts',
'categories')->together()->findAll();


: , 1.0.4.
, , Yii
( ).
, , ,
..
, HAS_MANY (, )
MANY_MANY (, ,
).

. relations()
CActiveRecord.
class Post extends CActiveRecord
{
public function relations()
{
return array(
'commentCount'=>array(self::STAT, 'Comment', 'post_id'),
'categoryCount'=>array(self::STAT, 'Category', 'post_category(post_id,
category_id)'),
);
}
}

: commentCount
, categoryCount , . ,
Post Comment HAS_MANY, Post Category
MANY_MANY ( post_category). ,
, .
, STAT.
,
$post->commentCount.
SQL-. ,
. ,
:
$posts=Post::model()->with('commentCount', 'categoryCount')->findAll();

69

Yii
SQL-
.
2*N+1 SQL- N .
COUNT.
relations().
:
select: , COUNT(*),
;
defaultValue: , ,
. , ,
commentCount . 0;
condition: WHERE, ;
params: SQL-.
-;
order: ORDER BY, ;
group: GROUP BY, ;
having: HAVING, .


: , 1.0.5.
.
.
:
$posts=Post::model()->published()->recently()->with('comments')->findAll();
. ,
with() .
.
, :
$posts=Post::model()->with('comments:recently:approved')->findAll();
. comments
. recently approved , Comment.
.

CActiveRecord::relations() with. $user->posts
.
class User extends CActiveRecord
{
public function relations()
{
return array(
'posts'=>array(self::HAS_MANY, 'Post', 'author_id',
'with'=>'comments:approved'),
);
}
}

: , ,
CActiveRecord::scopes, .

70

Yii

-.
,
.
Yii , , .
, , memcache -.
array(

'components'=>array(

'cache'=>array(
'class'=>'system.caching.CMemCache',
'servers'=>array(
array('host'=>'server1', 'port'=>11211, 'weight'=>60),
array('host'=>'server2', 'port'=>11211, 'weight'=>40),
),
),
),
);
, , :
Yii::app()->cache.
Yii -, . ,
CMemCache memcache PHP
; CApcCache APC PHP; CDbCache
. :
CMemCache: memcache PHP;
CApcCache: APC PHP;
CXCache: XCache PHP. 1.0.1;
CEAcceleratorCache: EAccelerator PHP;
CDbCache: .
SQLite3 .
connectionID;
CZendDataCache: Zend Data Cache. 1.0.4;
CFileCache: .
, . 1.0.6;
CDummyCache: -. . ,
.
, .
, .
Yii::app()->cache->get($key). ,
Yii::app()->cache null. 1.0.5.
: CCache,
, .
.
() , ,
. , ,
.
.
,
.

71

Yii
: , .
, .
(, ).


PHP .
CCache : set() get().
$value (ID)
set() :
Yii::app()->cache->set($id, $value);
, -
(, ,
).
set(). :
// 30
Yii::app()->cache->set($id, $value, 30);
, ( ),
get() . false,
( ).
$value=Yii::app()->cache->get($id);
if($value===false)
{
// $value, .. ,
// :
// Yii::app()->cache->set($id,$value);
}
, ,
, . ,
,
.
-, MemCache, APC,
, ,
. 1.0.8, mget() .
, - , mget() - .
delete(),
flush(). flush(), ..
.
: CCache ArrayAccess,
. :
$cache=Yii::app()->cache;
$cache['var1']=$value1;

// $cache->set('var1',$value1);

$value2=$cache['var2'];

// $value2=$cache->get('var2');


72

Yii
,
(dependency). ,
, ,
, .
CCacheDependency , .
, set().
// 30
// , ,
Yii::app()->cache->set($id, $value, 30, new CFileCacheDependency('FileName'));
, $value , get(),
, , false, ,
.
:
CFileCacheDependency: , ;
CDirectoryCacheDependency: ,
;
CDbCacheDependency: ,
SQL ;
CGlobalStateCacheDependency: ,
. ,
.
CApplication::setGlobalState();
CChainedCacheDependency: , ;
CExpressionDependency: , PHP
. 1.0.4.


. ,
,
, .
CController::beginCache()
CController::endCache() .
, . ,
.
HTML-
<?php if($this->beginCache($id)) { ?>

<?php $this->endCache(); } ?>
HTML-
, beginCache() false,
, , if
, endCache().


beginCache(), ,
. , beginCache()
endCache() COutputCache. ,
COutputCache.

( )
, duration, ,
().
CCache::set(). :

73

Yii

HTML-
<?php if($this->beginCache($id, array('duration'=>3600))) { ?>

<?php $this->endCache(); } ?>
HTML-
( ), (60 ).
, 60 .

,
(dependency). , ,
.
, dependency,
, ICacheDependency, ,
. ,
lastModified:
HTML-
<?php if($this->beginCache($id, array('dependency'=>array(
'class'=>'system.caching.dependencies.CDbCacheDependency',
'sql'=>'SELECT MAX(lastModified) FROM Post')))) { ?>

<?php $this->endCache(); } ?>
HTML-

()
. ,
- .
,
. -, ,
beginCache().
, ,
, COutputCache, .
:
varyByRoute: true,
. ,
;
varyBySession: true,
. ,
;
varyByParam: ,
GET . ,
GET- id,
varyByParam array('id') .
, ;
varyByExpression: PHP,
PHP. 1.0.4.


, .
, , (GET
) ( ). ( POST )
( ) , ,
. , requestTypes:
HTML

74

Yii

<?php if($this->beginCache($id, array('requestTypes'=>array('GET')))) { ?>



<?php $this->endCache(); } ?>
HTML


. ,
( ), . ,
,
.
HTML
<?php if($this->beginCache($id1)) { ?>

<?php if($this->beginCache($id2)) { ?>

<?php $this->endCache(); } ?>

<?php $this->endCache(); } ?>
HTML
. ,
.
,
. , .
, ,
( ).


.
. , ,
. -
.
.
. - ,
,
, beginCache() endCache(). ,
CController::render()
.
.
COutputCache .
, :
public function filters()
{
return array(
array(
'COutputCache',
'duration'=>100,
'varyByParam'=>array('id'),
),
);

75

Yii

}
, .
+.
.
: COutputCache ,
CFilterWidget, .. . ,
: () ,
() (), ()
, () ().


, ,
, .
,
, .

, ( )
, .
,
. ,
CController.
, ,
. ,
, . ,
, .
CController::renderDynamic() .
HTML-
<?php if($this->beginCache($id)) { ?>

<?php $this->renderDynamic($callback); ?>

<?php $this->endCache(); } ?>
HTML-
, $callback PHP-.
. ,
. renderDynamic()
. , .

Yii

Yii . ,
, Yii CController;
CWidget .
, (extension).
, . , Yii,
:

76

Yii

;
;
;
;
;
;
;
: , CValidator;
: , , ,
;
: , , ,
. .
, . , ,
.
, . Yii
,
.


, , :
1. Yii;
2. extensions/xyz , xyz
;
3. , .
. xyz, ,
ext.xyz, ,
.
: ext 1.0.8.
application.extensions , . ,
, ext. , 1.0.7 ,
ext application.extensions.
, .
, ,
.

Zii
, ,
Zii , Yii
Yii 1.1.0. Zii Google Code zii.
Zii,
zii.path.to.ClassName. zii Yii ,
Zii. , CGridView,
:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
));



, components:
return array(
// 'preload'=>array('xyz',),
'components'=>array(

77

Yii

'xyz'=>array(
'class'=>'ext.xyz.XyzClass',
'property1'=>'value1',
'property2'=>'value2',
),
//
),
);
Yii::app()->xyz.
(.. ), , ,
preload.

. :
. :
// $name
$component->attachBehavior($name,$behavior);
// test() $behavior
$component->test();
,
attachBehavior. , ,
:
return array(
'components'=>array(
'db'=>array(
'class'=>'CDbConnection',
'behaviors'=>array(
'xyz'=>array(
'class'=>'ext.xyz.XyzBehavior',
'property1'=>'value1',
'property2'=>'value2',
),
),
),
//
),
);
xyz db.
CApplicationComponent behaviors.
.
CController, CFormModel CActiveRecord, ,
behaviors(). ,
, . :
public function behaviors()

78

Yii

{
return array(
'xyz'=>array(
'class'=>'ext.xyz.XyzBehavior',
'property1'=>'value1',
'property2'=>'value2',
),
);
}

. XyzClass xyz,
:
//
<?php $this->widget('ext.xyz.XyzClass', array(
'property1'=>'value1',
'property2'=>'value2')); ?>
// ,
<?php $this->beginWidget('ext.xyz.XyzClass', array(
'property1'=>'value1',
'property2'=>'value2')); ?>

<?php $this->endWidget(); ?>

. XyzClass
xyz CController::actions
:
class TestController extends CController
{
public function actions()
{
return array(
'xyz'=>array(
'class'=>'ext.xyz.XyzClass',
'property1'=>'value1',
'property2'=>'value2',
),
//
);
}

79

Yii

}
test/xyz.

.
- - . XyzClass
xyz CController::filters :
class TestController extends CController
{
public function filters()
{
return array(
array(
'ext.xyz.XyzClass',
'property1'=>'value1',
'property2'=>'value2',
),
//
);
}
}
'+' '-'
. CController.

, .
CWebApplication::controllerMap
:
return array(
'controllerMap'=>array(
'xyz'=>array(
'class'=>'ext.xyz.XyzClass',
'property1'=>'value1',
'property2'=>'value2',
),
//
),
);
a xyz/a.

( CFormModel CActiveRecord).
XyzClass xyz CModel::rules
:
class MyModel extends CActiveRecord // or CFormModel
{
public function rules()

80

Yii

{
return array(
array(
'attr1, attr2',
'ext.xyz.XyzClass',
'property1'=>'value1',
'property2'=>'value2',
),
//
);
}
}


, ,
yiic. XyzClass xyz ,
:
return array(
'commandMap'=>array(
'xyz'=>array(
'class'=>'ext.xyz.XyzClass',
'property1'=>'value1',
'property2'=>'value2',
),
//
),
);

yiic xyz.
: , , . yiic webapp,
protected/yiic protected/config/console.php, protected/config/main.php.


, :
Yii::import('ext.xyz.XyzClass');
, , .
, .


81

Yii
,
. ,
:
, ..
. ,
, ;
,
;
,
;
API ,
, ;
. ,
, ,
BSD, MIT ., GPL, .. , ,
, .
, ,
. ,
.


IApplicationComponent
CApplicationComponent. , , IApplicationComponent::init.
. ,
, .
,
.
,
CApplication::preload.

, IBehavior. Yii
CBehavior, .
, ,
.
CModel CActiveRecord CModelBehavior ,
, CActiveRecordBehavior. ,
CModel CActiveRecord. , CActiveRecordBehavior
ActiveRecord. , ,
, AR.
ActiveRecord. AR
save(), create_time update_time
.
class TimestampBehavior extends CActiveRecordBehavior
{
public function beforeSave($event)
{
if($this->owner->isNewRecord)
$this->owner->create_time=time();
else
$this->owner->update_time=time();
}
}

CWidget .

. , CSS-

82

Yii
CTabView, , , CTabView::cssFile.
CTabView, ,
:
class MyTabView extends CTabView
{
public function init()
{
if($this->cssFile===null)
{
$file=dirname(__FILE__).DIRECTORY_SEPARATOR.'tabview.css';
$this->cssFile=Yii::app()->getAssetManager()->publish($file);
}
parent::init();
}
}
CWidget::init , CTabView::cssFile ,
URL CSS- . CSS-
MyTabView, .
CSS- , .
, , , : CWidget::init CWidget::run.
, $this->beginWidget
, $this->endWidget.

CWidget::init
CWidget::run.
, , CSS-, JavaScript
. , ,
, -. , ,
, CWebApplication::assetManager, .
, CSS- JavaScript ,
CClientScript:
class MyWidget extends CWidget
{
protected function registerClientScript()
{
// CSS JavaScript
$cs=Yii::app()->clientScript;
$cs->registerCssFile($cssFile);
$cs->registerScriptFile($jsFile);
}
}
.
views .
$this->render('ViewName'),
.

CAction . IAction::run ,
.

83

Yii
CFilter . ,
, CFilter::preFilter CFilter::postFilter.
, .
class MyFilter extends CFilter
{
protected function preFilter($filterChain)
{
//
return true; // false ,
}
protected function postFilter($filterChain)
{
//
}
}
$filterChain CFilterChain, ,
.

, , CExtController,
CController. , CController ,
application.views.ControllerID,
CExtController , views,
. , - ,
.

CValidator CValidator::validateAttribute.
class MyValidator extends CValidator
{
protected function validateAttribute($model,$attribute)
{
$value=$model->$attribute;
if($value has error)
$model->addError($attribute,$errorMessage);
}
}


CConsoleCommand
CConsoleCommand::run. CConsoleCommand::getHelp,
.
class MyCommand extends CConsoleCommand
{
public function run($args)
{
// $args ,
}

84

Yii

public function getHelp()


{
return 'Usage: how to use this command';
}
}

.
, ,
(CSS, JavaScript, ), ,
, , -.


. , ,
.
;

: , , Yii 1.1. ,
, , Yii 1.0.x.
, PHPUnit SimpleTest,
.
. ,
, . ,
PHP- echo die ,
. , HTML-,
, . ,
.
.
Yii .
, , .
. ,
. , , ,
. , .
, (, )
. , ,
.
, ( ,
QA).


(TDD):
1. , . , ,
, .
2. . , .
3. , .
4. . , .
5. , .
1 5 .


Yii PHPUnit 3.4+ Selenium Remote Control 1.0+.
PHPUnit Selenium Remote Control .

85

Yii
yiic webapp
, :
testdrive/
protected/

tests/

fixtures/

functional/

unit/

report/

bootstrap.php

phpunit.xml

PHPUnit

WebTestCase.php

, : fixtures, functional
unit. report .
, ( , ),
:
% cd testdrive/protected/tests
% phpunit functional/PostTest.php //
% phpunit --verbose functional

// 'functional'

% phpunit --coverage-html ./report unit


unit
report. , xdebug.


, bootstrap.php. ,
,
.
$yiit='path/to/yii/framework/yiit.php';
$config=dirname(__FILE__).'/../config/test.php';
require_once($yiit);
require_once(dirname(__FILE__).'/WebTestCase.php');
Yii::createWebApplication($config);
yiit.php,
.
, test.php. main.php
fixture ( CDbFixtureManager).
.
return CMap::mergeArray(
require(dirname(__FILE__).'/main.php'),
array(
'components'=>array(
'fixture'=>array(
'class'=>'system.test.CDbFixtureManager',
),
/* ,
'db'=>array(

86

Yii

'connectionString'=>'DSN ',
),
*/
),
)
);
, , ,
, .
db DSN connectionString.
,
. ,
.


.
.
. , , ,
, , (, Post,
Comment), . PHPUnit
.
, .
, ,
-. Yii CDbFixtureManager
. :
,
.

.
,
.
CDbFixtureManager,
:
return array(
'components'=>array(
'fixture'=>array(
'class'=>'system.test.CDbFixtureManager',
),
),
);
protected/tests/fixtures.
CDbFixtureManager::basePath .
PHP-, .
, . , . Post,
Post.php:
<?php
return array(

87

Yii

'sample1'=>array(
'title'=>' 1',
'content'=>' 1',
'createTime'=>1230952187,
'authorId'=>1,
),
'sample2'=>array(
'title'=>' 2',
'content'=>' 2',
'createTime'=>1230952287,
'authorId'=>1,
),
);
, 2 .
, , -
. , ( sample1, sample2),
. , ,
. .
, id . ,
id ,
.
CDbFixtureManager
. , ,
, .
, , ,
, . ,
PHP- . PHP-
init.php , .
CDbFixtureManager , ,
.
, , ,
. ,
. , ,
- .init.php. , Post Post.init.php.
CDbFixtureManager , ,
.
:
. , ,
. , , , ,
.
, ,
CDbFixtureManager, .


Yii PHPUnit,
PHPUnit, , .
Yii:
XyzTest, CTestCase CDbTestCase, Xyz
. , Post
PostTest. CTestCase
, CDbTestCase

88

Yii
Active Record. ,
PHPUnit_Framework_TestCase, (CTestCase
CDbTestCase).
PHP- XyzTest.php.
protected/tests/unit.
testAbc,
Abc .
(,
assertTrue, assertEquals),
.
, Active Record.
, CDbTestCase,
, .
, Comment -.
CommentTest protected/tests/unit/CommentTest.php:
class CommentTest extends CDbTestCase
{
public $fixtures=array(
'posts'=>'Post',
'comments'=>'Comment',
);

}
- fixtures , ,
.
(, posts Post).
,
: (, :Post), .
, .
,
.
.
:
// `Comment`
$comments = $this->comments;
// 'sample1' `Post`
$post = $this->posts['sample1'];
// AR, 'sample1'
$post = $this->posts('sample1');

: (,
'posts'=>':Post'), ,
, .
testApprove approve Comment.
: , ,
, , , ,
approve , , .

89

Yii

public function testApprove()


{
//
$comment=new Comment;
$comment->setAttributes(array(
'content'=>'comment 1',
'status'=>Comment::STATUS_PENDING,
'createTime'=>time(),
'author'=>'me',
'email'=>'me@example.com',
'postId'=>$this->posts['sample1']['id'],
),false);
$this->assertTrue($comment->save(false));
//
$comment=Comment::model()->findByPk($comment->id);
$this->assertTrue($comment instanceof Comment);
$this->assertEquals(Comment::STATUS_PENDING,$comment->status);

// approve() ,
$comment->approve();
$this->assertEquals(Comment::STATUS_APPROVED,$comment->status);
$comment=Comment::model()->findByPk($comment->id);
$this->assertEquals(Comment::STATUS_APPROVED,$comment->status);
}


1.1.2, Yii - , Gii.
yiic shell. ,
Gii .

Gii
Gii Yii.
Gii :
return array(

'modules'=>array(
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>' ',
// 'ipFilters'=>array( IP),
// 'newFileMode'=>0666,
// 'newDirMode'=>0777,
),

90

Yii

),
);
gii GiiModule. ,
Gii.
, , Gii localhost.
, GiiModule::ipFilters .
Gii ,
, - .
GiiModule::newFileMode GiiModule::newDirMode ,
.
: Gii .
.
PHP, (, IP ).
Gii URL http://hostname/path/to/index.php?r=gii,
http://hostname/path/to/index.php URL .
URL path (. URL),
Gii URL http://hostnamepath/to/index.php/gii.
URL :
'components'=>array(

'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'gii'=>'gii',
'gii/<controller:w+>'=>'gii/<controller>',
'gii/<controller:w+>/<action:w+>'=>'gii/<controller>/<action>',

),
),
)
Gii . .
,
; ActiveRecord .
:
1. ;
2. , . ,
ID;
3. Preview .
, ;
4. Generate ;
5. .

Gii
, Gii ,
. ,
.
Gii.
Gii :
.

91

Yii


, .
:
model/

ModelCode.php

ModelGenerator.php

views/

index.php

templates/

default/

'default'

model.php


Gii , GiiModule::generatorPaths. ,
, :
return array(
'modules'=>array(
'gii'=>array(
'class'=>'system.gii.GiiModule',
'generatorPaths'=>array(
'application.gii',

//

),
),
),
);
Gii
application.gii system.gii.generators.
, .
, GiiModule::generatorPaths.


Gii.
, , . ,
, .
protected/gii/model/templates/compact. model ,
. templates/compact
compact.
GiiModule::generatorPaths
application.gii, .
. Code Template.
, compact.
, , . ,
compact .
framework/gii/generators/model/templates/default/model.php
protected/gii/model/templates/compact. compact
, . , ,
default.
.
protected/gii/model/templates/compact/model.php.
, , PHP.

92

Yii
, attributeLabels() Yii::t()
:
public function attributeLabels()
{
return array(
<?php foreach($labels as $name=>$label): ?>
<?php echo "'$name' => Yii::t('application', '$label'),
"; ?>
<?php endforeach; ?>
);
}
, ,
, $labels. .
.
.


, ,
.
protected/gii/widget. :
WidgetGenerator.php: WidgetGenerator,
.
WidgetCode.php: WidgetCode,
.
views/index.php: , .
templates/default/widget.php: .
WidgetGenerator.php
WidgetGenerator.php . :
class WidgetGenerator extends CCodeGenerator
{
public $codeModel='application.gii.widget.WidgetCode';
}
, ,
application.gii.widget.WidgetCode. WidgetGenerator CCodeGenerator,
, ,
.
WidgetCode.php
WidgetCode.php WidgetCode,
. ,
, . WidgetCode
:
class WidgetCode extends CCodeModel
{
public $className;
public function rules()
{
return array_merge(parent::rules(), array(
array('className', 'required'),

93

Yii

array('className', 'match', 'pattern'=>'/^w+$/'),


));
}
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), array(
'className'=>'Widget Class Name',
));
}
public function prepare()
{
$path=Yii::getPathOfAlias('application.components.' . $this->className) . '.php';
$code=$this->render($this->templatepath.'/widget.php');
$this->files[]=new CCodeFile($path, $code);
}
}
WidgetCode CCodeModel. ,
rules() attributeLabels()
. , CCodeModel
,
.
prepare() .
CCodeFile, .
CCodeFile, ,
protected/components. CCodeFile::render.
PHP- .
views/index.php
(WidgetGenerator) (WidgetCode)
views/index.php:
<h1> </h1>
<?php $form=$this->beginWidget('CCodeForm', array('model'=>$model)); ?>
<div class="row">
<?php echo $form->labelEx($model,'className'); ?>
<?php echo $form->textField($model,'className',array('size'=>65)); ?>
<div class="tooltip">
.
</div>
<?php echo $form->error($model,'className'); ?>
</div>

94

Yii

<?php $this->endWidget(); ?>


, CCodeForm.
className WidgetCode.
CCodeForm.
. .
,
, .
: div CSS tooltip.

, .
.
. .
, , .
-, sticky . ,

baseClass actions:
public function rules()
{
return array_merge(parent::rules(), array(

array('baseClass, actions', 'sticky'),


));
}
-, CSS sticky div :
<div class="row sticky">

</div>

templates/default/widget.php
, templates/default/widget.php. ,
PHP- .
$this, . $this WidgetModel.
, $this->className.
<?php echo '<?php'; ?>
class <?php echo $this->className; ?> extends CWidget
{
public function run()
{
}
}
. URL
http://hostname/path/to/index.php?r=gii/widget.

95

Yii


URL
URL- - . -,
, URL, . , URL,
. Yii- CUrlManager.

URL
, URL ,
:
$url=$this->createUrl($route,$params);
$this ; $route , $params
GET URL.
, createUrl get-. ,
$route='post/read' $params=array('id'=>100), URL:
/index.php?r=post/read&id=100
=, &, r
. , .
, , ,
path,
GET- URL:
/index.php/post/read/id/100
URL, urlManager
, createUrl
, URL:
array(

'components'=>array(

'urlManager'=>array(
'urlFormat'=>'path',
),
),
);
, urlManager , ..
CUrlManager CWebApplication.
: URL, createUrl . ,
, , Yii::app()->request->hostInfo,
createAbsoluteUrl.

URL
URL path,
URL, . ,
/post/100

96

Yii
/index.php/post/read/id/100. CUrlManager URL ,
.
URL rules
urlManager:
array(

'components'=>array(

'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'pattern1'=>'route1',
'pattern2'=>'route2',
'pattern3'=>'route3',
),
),
),
);

-, .
, URL.
.
,
:
'pattern1'=>array('route1', 'urlSuffix'=>'.xml', 'caseSensitive'=>false)
. 1.1.0,
:
urlSuffix: URL, .
null, CUrlManager::urlSuffix.
caseSensitive: . null,
CUrlManager::caseSensitive.
defaultParams: GET- (=>) .
$_GET.
matchValue: GET- URL
. null,
CUrlManager::matchValue. false
URL
. true
. , true
.


GET-.
:
<ParamName:ParamPattern>
ParamName GET-, ParamPattern
, GET-.
ParamPattern , , /.
URL ,
URL, GET- .

97

Yii
. ,
:
array(
'posts'=>'post/list',
'post/<id:d+>'=>'post/read',
'post/<year:d{4}>/<title>'=>'post/read',
)

$this->createUrl('post/list') /index.php/posts.
.
$this->createUrl('post/read',array('id'=>100))
/index.php/post/100. .
$this->createUrl('post/read',array('year'=>2008,'title'=>'a sample
post')) /index.php/post/2008/a%20sample%20post.
.
$this->createUrl('post/read') /index.php/post/read.
.
createUrl URL, GET-, ,
, . ,
, , GET-,
.
GET- , ,
. , $this>createUrl('post/read',array('id'=>100,'year'=>2008)),
/index.php/post/100?year=2008. ,
, /*. ,
post/<id:d+>/* URL /index.php/post/100/year/2008.
, URL URL-.
URL. , /index.php/post/100,
post/read GET-
array('id'=>100) ( $_GET).
: URL .
, URL CUrlManager
, - . ,
. URL
.


1.0.5,
. , .
, , .
, , :
array(
'<_c:(post|comment)>/<id:d+>/<_a:(create|update|delete)>' => '<_c>/<_a>',
'<_c:(post|comment)>/<id:d+>' => '<_c>/read',
'<_c:(post|comment)>s' => '<_c>/list',
)
: _c _a.
post comment, action-
create, update delete. -,
GET-, URL.

98

Yii
, , URL /index.php/post/123/create
post/create GET- id=123. comment/list GET-
page=2, URL /index.php/comments?page=2.


1.0.11 URL.
GET-. , URL
http://admin.example.com/en/profile GET- user=admin
lang=en. , URL
.
, URL:
array(
'http://<user:w+>.example.com/<lang:w+>/profile' => 'user/profile',
)
, user,
lang. user/profile.
, CUrlManager::showScriptName URL
.
,
, . ,
http://www.example.com/sandbox/blog,
URL, . : sandbox/blog.

index.php
URL
index.php. - urlManager.
- , URL
. Apache HTTP server
URL .
/wwwroot/blog/.htaccess, , .
Apache Directory /wwwroot/blog.
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
showScriptName urlManager false.
, $this->createUrl('post/read',array('id'=>100)), URL /post/100.
, URL -.

URL
, URL .
, /post/100.html /post/100,
. urlManager
urlSuffix .


99

Yii
, .
, , .
, , , . ,
( ).
, , .
Yii (auth), , ,
.
auth-
, IWebUser.
. ,
Yii::app()->user.
, , ,
CWebUser::isGuest. .
CWebUser::checkAccess.
.

Identity
, , Identity,
. IUserIdentity.
( OpenID LDAP) .
CUserIdentity, .
Identity IUserIdentity::authenticate.
,
.
, ,
Active Record. getId ,
_id, (
ID ). , CBaseUserIdentity::setState,
title .
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$record=User::model()->findByAttributes(array('username'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==md5($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
$this->setState('title', $record->title);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}

100

Yii

}
, , ( CBaseUserIdentity::setState)
CWebUser, , .
CWebUser. , title
Yii::app()->user->title ( 1.0.3. ,
: Yii::app()->user->getState('title'))
: CWebUser .
cookie (CWebUser::allowAutoLogin true),
cookie. ,
, .


Identity User,
:
//
$identity=new UserIdentity($username,$password);
if($identity->authenticate())
Yii::app()->user->login($identity);
else
echo $identity->errorMessage;

//
Yii::app()->user->logout();

cookie
, , ,
. , , User
allowAutoLogin true cookie CWebUser::login.
,
. cookie .
// 7 .
// allowAutoLogin user true.
Yii::app()->user->login($identity,3600*24*7);
, cookie, ,
CBaseUserIdentity::setState, cookie.
cookie Yii::app()->user.
, Yii cookie
, .
(, ).
, cookie
:
cookie
, (.. ).
cookie
.
, .
cookie,
.

101

Yii
:
CUserIdentity::authenticate(). .
, (
CBaseUserIdentity::setState) .
CWebUser::beforeLogin(). .
.


,
.
, IP- . accessControl.
: .
(RBAC), .
CController::filters
( ).
class PostController extends CController
{

public function filters()


{
return array(
'accessControl',
);
}
}
, access control
PostController. ,
CController::accessRules .
class PostController extends CController
{

public function accessRules()


{
return array(
array('deny',
'actions'=>array('create', 'edit'),
'users'=>array('?'),
),
array('allow',
'actions'=>array('delete'),
'roles'=>array('admin'),
),
array('deny',
'actions'=>array('delete'),
'users'=>array('*'),
),

102

Yii

);
}
}
, .
'allow'() 'deny'(). -,
. , : create edit
, delete
admin.
. ,
(, , IP) .
, , .
.
: , ,
, , :
return array(
//
// 'delete'
array('deny',
'actions'=>array('delete'),
),
);

, , .
, :
actions: .
;
controllers: .
. 1.0.4;
users: . CWebUser::name.
. :
o *: , .
o ?: .
o @: .
roles: , , .
, , CWebUser::checkAccess true
.
- . , , ,
, auth-,
, ;
ips: IP-;
verbs: (, GET POST). ;
expression: PHP,
. $user, Yii::app()->user.
1.0.3.


, .. ,
:

103

Yii

loginUrl user URL


, . , loginUrl
site/login;
HTTP 403.
loginUrl , URL.
, CWebApplication::createUrl URL.
login , GET-. ,
array(

'components'=>array(
'user'=>array(
//
'loginUrl'=>array('site/login'),
),
),
)
,
, . URL
? returnUrl user. ,
:
Yii::app()->request->redirect(Yii::app()->user->returnUrl);


(RBAC) ,
. .
Yii RBAC authManager.
, , , . ,
.


RBAC Yii .
- ( , ).
, ,
. . . -
( ). , ,
.
,
. , Yii .
. .
.
- PHP-,
.
true. , updatePost, -,
ID ID . ,
.
. A
B , A B ( A , B).
.
, . ,
. .

. , . ,
, ,

104

Yii
( ,
).
. ,
. RBAC ,
:
if(Yii::app()->user->checkAccess('deletePost'))
{
//
}


, ,
authManager. Yii
: CPhpAuthManager CDbAuthManager. PHP,
. authManager ,
. ,
return array(
'components'=>array(
'db'=>array(
'class'=>'CDbConnection',
'connectionString'=>'sqlite:path/to/file.db',
),
'authManager'=>array(
'class'=>'CDbAuthManager',
'connectionID'=>'db',
),
),
);
authManager Yii::app()->authManager.


: ,
. authManager
API .
:
CAuthManager::createRole
CAuthManager::createTask
CAuthManager::createOperation
, ,
:
CAuthManager::addItemChild
CAuthManager::removeItemChild
CAuthItem::addChild
CAuthItem::removeChild
:
CAuthManager::assign
CAuthManager::revoke
API:
$auth=Yii::app()->authManager;

105

Yii

$auth->createOperation('createPost',' ');
$auth->createOperation('readPost',' ');
$auth->createOperation('updatePost',' ');
$auth->createOperation('deletePost',' ');
$bizRule='return Yii::app()->user->id==$params["post"]->authID;';
$task=$auth->createTask('updateOwnPost',' ',$bizRule);
$task->addChild('updatePost');
$role=$auth->createRole('reader');
$role->addChild('readPost');
$role=$auth->createRole('author');
$role->addChild('reader');
$role->addChild('createPost');
$role->addChild('updateOwnPost');
$role=$auth->createRole('editor');
$role->addChild('reader');
$role->addChild('updatePost');
$role=$auth->createRole('admin');
$role->addChild('editor');
$role->addChild('author');
$role->addChild('deletePost');
$auth->assign('reader','readerA');
$auth->assign('author','authorB');
$auth->assign('editor','editorC');
$auth->assign('admin','adminD');
, authManager ( , ,
CPhpAuthManager, CDbAuthManager) .
, , .
: .

.

-
, -.
. - PHP-,
. ,
. -
updateOwnPost. , ID ID .
$params .


106

Yii
. , ,
, , ,
createPost. CWebUser::checkAccess:
if(Yii::app()->user->checkAccess('createPost'))
{
//
}
-, ,
. , , ,
:
$params=array('post'=>$post);
if(Yii::app()->user->checkAccess('updateOwnPost',$params))
{
//
}


: 1.0.3
- ,
. ,
.
. .
, .
CWebUser::checkAccess . .
CAuthManager::defaultRoles. ,
: authenticated guest.
return array(
'components'=>array(
'authManager'=>array(
'class'=>'CDbAuthManager',
'defaultRoles'=>array('authenticated', 'guest'),
),
),
);
, , , . ,
: authenticated guest,
.
$bizRule='return !Yii::app()->user->isGuest;';
$auth->createRole('authenticated', ' ', $bizRule);
$bizRule='return Yii::app()->user->isGuest;';
$auth->createRole('guest', '', $bizRule);

107

Yii


-.
, .
Yii , ,
, , CSS, JavaScript .
. WebRoot/themes, , ..
, .
: , WebRoot/themes
basePath baseUrl themeManager .


theme .
.
: , , ,
Yii::app()->theme null.


,
, , views,
views/layouts, views/system. ,
create PostController
classic,
WebRoot/themes/classic/views/post/create.php.
,
views. , PostController
forum, create
WebRoot/themes/classic/views/forum/post/create.php. forum
support,
WebRoot/themes/classic/views/support/forum/post/create.php.
: views ,
.
render renderPartial
. ,
, , ,
viewPath layoutPath.
: , ,
, images. baseUrl ,
:
Yii::app()->theme->baseUrl . '/images/FileName.gif'

basic fancy:
WebRoot/
assets
protected/
.htaccess

108

Yii

components/
controllers/
models/
views/
layouts/
main.php
site/
index.php
themes/
basic/
views/
.htaccess
layouts/
main.php
site/
index.php
fancy/
views/
.htaccess
layouts/
main.php
site/
index.php

, :
return array(
'theme'=>'basic',

);
basic. (layout)
themes/basic/views/layouts, index themes/basic/views/site.
, protected/views.


1.1.5, , , .
CWidget::render() , Yii ,
.
xyz Foo, Foo (
, ) .
( PHP 5.3.0), appwidgetsFoo,
app_widgets_Foo. .
xyz.php .
themes/basic/views/Foo/xyz.php,
, basic.


: 1.1.3.

109

Yii
, , , . ,
CLinkPager::maxButtonCount 10 ( ) 5.
CBaseController::widget .
, , CLinkPager .
$this->widget('CLinkPager', array(
'pages'=>$pagination,
'maxButtonCount'=>5,
'cssFile'=>false,
));
,
. widgetFactory :
return array(
'components'=>array(
'widgetFactory'=>array(
'widgets'=>array(
'CLinkPager'=>array(
'maxButtonCount'=>5,
'cssFile'=>false,
),
'CJuiDatePicker'=>array(
'language'=>'ru',
),
),
),
),
);
CLinkPager CJuiDatePicker
CWidgetFactory::widgets. ,
- , ,
.
, CLinkPager ,
. ,
:
$this->widget('CLinkPager', array(
'pages'=>$pagination,
));
, . , maxButtonCount 2, :
$this->widget('CLinkPager', array(
'pages'=>$pagination,
'maxButtonCount'=>2,
));

110

Yii

: 1.1.0.
, ,
, .
-, .
, ,
. , classic CLinkPager.
, ,
, CWidgetFactory::enableSkin widgetFactory true:
return array(
'components'=>array(
'widgetFactory'=>array(
'enableSkin'=>true,
),
),
);
Yii 1.1.3 :
return array(
'components'=>array(
'widgetFactory'=>array(
'class'=>'CWidgetFactory',
),
),
);
. , ,
PHP, .
protected/views/skins.
skinPath widgetFactory. ,
protected/views/skins CLinkPager.php, :
<?php
return array(
'default'=>array(
'nextPageLabel'=>'&gt;&gt;',
'prevPageLabel'=>'&lt;&lt;',
),
'classic'=>array(
'header'=>'',
'maxButtonCount'=>5,
),
);
CLinkPager : default classic.
CLinkPager, skin,

111

Yii
, skin classic. ,
default, classic:
<?php $this->widget('CLinkPager'); ?>
<?php $this->widget('CLinkPager', array('skin'=>'classic')); ?>
,
. ,
, array('header'=>'',
'maxButtonCount'=>6, 'cssFile'=>false),
, , classic.
<?php $this->widget('CLinkPager', array(
'skin'=>'classic',
'maxButtonCount'=>6,
'cssFile'=>false,
)); ?>
, . , , Yii
skins (,
WebRoot/themes/classic/views/skins). ,
,
.
, Yii - ,
- .
: , Yii
, .
. :
, ;
;
;
, .

Yii .
.
, , , ..


Yii::log Yii::trace.
, , .
Yii::log($message, $level, $category);
Yii::trace($message, $category);
, .
xxx.yyy.zzz,
. , CController,
system.web.CController. :
trace: Yii::trace.
;
info: ;
profile: () ;

112

Yii

warning: -;
error: .


, Yii::log Yii::trace, . ,
, ,
. .
Yii CLogRouter.
.
. , ,
.
, ,
CLogRouter. , routes
, , .
:
array(

'preload'=>array('log'),
'components'=>array(

'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'trace, info',
'categories'=>'system.*',
),
array(
'class'=>'CEmailLogRoute',
'levels'=>'error, warning',
'emails'=>'admin@example.com',
),
),
),
),
)
, . - CFileLogRoute -
runtime. trace
info system.. - CEmailLogRoute -
. error warning.
Yii :
CDbLogRoute: ;
CEmailLogRoute: ;
CFileLogRoute: ;
CWebLogRoute: ;
CProfileLogRoute: .
: ,
, onEndRequest.

113

Yii
, CApplication::end() die() exit(). CApplication::end()
onEndRequest, .


, ,
. levels categories
. ,
.
xxx.yyy.zzz,
. , , xxx xxx.yyy,
xxx.yyy.zzz. xxx, xxx.*.


1.0.6, ,
PHP ($_GET, $_SERVER), ID , ..
CLogRoute::filter.
CLogFilter,
. , CLogFilter
, $_GET $_SERVER, .
CLogFilter , ID ,
, .
.
. .
array(

'preload'=>array('log'),
'components'=>array(

'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error',
'filter'=>'CLogFilter',
),
other log routes
),
),
),
)
1.0.7, Yii ,
Yii::trace. , , ..
. , YII_TRACE_LEVEL
( yii.php) . Yii
,
. YII_TRACE_LEVEL ,
. ,
, .

114

Yii
.

.
, , ,
. ,
:
Yii::beginProfile('blockID');

Yii::endProfile('blockID');
blockID .
, , ..
. , .
, ,
CProfileLogRoute, .
. CProfileLogRoute
.

SQL-
, SQL-
. ,
beginProfile endProfile , , SQL-,
1.0.6 Yii .
CDbConnection::enableProfiling true,
SQL-.
CProfileLogRoute, , SQL- .
CDbConnection::getStats().


Yii
5. ,
handleError ,
handleException . ,
, ,
.
:
set_exception_handler set_error_handler. , Yii
, false YII_ENABLE_ERROR_HANDLER
YII_ENABLE_EXCEPTION_HANDLER.
, errorHandler ( exceptionHandler) onError ( onException).
( ) ,
errorHandler.


Yii .
, :
throw new ExceptionClass('ExceptionMessage');
Yii : CException CHttpException.
, , .
, statusCode, .
, . .
: CHttpException ,
. , URL

115

Yii
, 404 ( )
:
//
throw new CHttpException(404,' ');


, CErrorHandler ,
. ,
, CHttpException, errorXXX,
XXX (400, 404, 500 ..).
, exception.
, .
: , , ,
errorXXX. ,
.
.
CErrorHandler , , :
1. WebRoot/themes/ThemeName/views/system:
;
2. WebRoot/protected/views/system: ,
;
3. yii/framework/views: ,
.
, ,
.
-, HTML-.
, ,
view.


1.0.6 Yii .
:
return array(

'components'=>array(
'errorHandler'=>array(
'errorAction'=>'site/error',
),
),
);
site/error, error SiteController,
CErrorHandler::errorAction. , .
error :
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
$this->render('error', $error);
}

116

Yii
CErrorHandler::error.
error. , CErrorHandler::error
, :
code: HTTP (, 403 500);
type: (, CHttpException PHP Error);
message: ;
file: PHP-, ;
line: , ;
trace: ;
source: , .
: CErrorHandler::error , .. error
. $error ,
, ,
$code $type.


, error . ,
,
php, ,
exception.ExceptionClassName ( CHttpException ).
, ,
.

-
- ,
. - API,
, -. , ,
Flex, , PHP-.
SOAP.
, -, Yii CWebService CWebServiceAction.
API , . Yii
WSDL, API .
, Yii , API
.
: CWebService PHP SOAP. , ,
, , .


, , ,
. , ,
, Yii reflection.
,
. , . ,
StockController CController. .
, , .
class StockController extends CController
{
/**
* @param string
* @return float
* @soap
*/

117

Yii

public function getPrice($symbol)


{
$prices=array('IBM'=>100, 'GOOGLE'=>350);
return isset($prices[$symbol])?$prices[$symbol]:0;
// $symbol
}
}
, getPrice API -,
@soap. .
API .

-
.
CWebServiceAction. StockController:
class StockController extends CController
{
public function actions()
{
return array(
'quote'=>array(
'class'=>'CWebServiceAction',
),
);
}
/**
* @param string
* @return float
* @soap
*/
public function getPrice($symbol)
{
// $symbol
}
}
, -. URL
http://hostname/path/to/index.php?r=stock/quote, XML,
WSDL -.
: , CWebServiceAction ,
. getPrice
StockController.

-
118

Yii
, , , -,
. PHP,
, Java, C#, Flex ..
$client=new SoapClient('http://hostname/path/to/index.php?r=stock/quote');
echo $client->getPrice('GOOGLE');
, 350,
GOOGLE.


, -,
.
:
str/string: xsd:string;
int/integer: xsd:int;
float/double: xsd:float;
bool/boolean: xsd:boolean;
date: xsd:date;
time: xsd:time;
datetime: xsd:dateTime;
array: xsd:string;
object: xsd:struct;
mixed: xsd:anyType.
, ,
. , public- ,
@soap.
. []
. .
API getPosts, Post.
class PostController extends CController
{
/**
* @return Post[]
* @soap
*/
public function getPosts()
{
return Post::model()->findAll();
}
}
class Post extends CActiveRecord
{
/**
* @var integer ID
* @soap
*/
public $id;
/**
* @var string
* @soap

119

Yii

*/
public $title;
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}


,
WSDL PHP. classMap CWebServiceAction.
class PostController extends CController
{
public function actions()
{
return array(
'service'=>array(
'class'=>'CWebServiceAction',
'classMap'=>array(
'Post'=>'Post',

// 'Post'

),
),
);
}


IWebServiceProvider,
. IWebServiceProvider::beforeWebMethod
CWebService. CWebService::methodName .
(, ) ,
false.

( I18N) ,

. - ,
.
Yii :
.
.
.
.


120

Yii
, ,
. ,
. , en_US
. Yii : LanguageID ()
LanguageID_RegionID (_) . : ru, en_us.
CLocale,
, , ,
. ,
CLocale . ,
.
, CLocale:
CLocale::getInstance($localeID) CApplication::getLocale($localeID).
: Yii .
Common Locale Data Repository (CLDR). ,
CLDR, .
1.1.0 .
CApplication::localeDataPath, ,
.
framework/i18n/data , .
Yii .
() , . ,
. ,
.

.
: .
CHttpRequest::preferredLanguage.

, , .
.
, .
, . Yii
, .
.


Yii::t().
.
,
(). yii
.
, Yii::t()
. , {alias}
:
Yii::t('app', 'Path alias "{alias}" is redefined.',
array('{alias}'=>$alias))

: , ("Invalid
{$message} content."). -
.
, .
CMessageSource .

121

Yii
Yii::t() ,
.
Yii , .
, CMessageSource.
CPhpMessageSource: - PHP.
, .
,
.
, , .
, basePath;
CGettextMessageSource: GNU Gettext;
CDbMessageSource: . .
CDbMessageSource.
. ,
, messages.
CPhpMessageSource. , protected/messages.
, , , :
1. Yii::t() ;
2. protected/messages/Id/.php.
. ,
CPhpMessageSource;
3. CApplication::sourceLanguage CApplication::language.
: CPhpMessageSource,
yiic. message
, , ,
. message
yiic help message.
1.0.10, CPhpMessageSource,
. , Xyz,
Xyz..
/messages/ID/.php, ,
. Yii::t()
:
Yii::t('Xyz.', ' ')
1.0.2, Yii .
. , 'book'
.
( )
( ). ,
.
, |:
'expr1#message1|expr2#message2|expr3#message3'
exprN PHP, . true
.
n ( $n!), , .
,
'n==1#one book|n>1#many books'
2 Yii::t(), many books.
, ,
n==Number:

122

Yii

'1#one book|n>1#many books'


CApplication::findLocalizedFile().
, . LocaleID.
, .
.
, .
, zh_cn, en_us
edit
protected/views/ControllerID/zh_cn/edit.php.
, ,
protected/views/ControllerID/edit.php.
. , ,
.


-.
, .
Yii CDateFormatter.
CDateFormatter .
, dateFormatter.
CDateFormatter , UNIX timestamp:
format: UNIX timestamp (,
$dateFormatter->format('dd.MM.yyyy', $timestamp));
formatDateTime: UNIX timestamp ,
( short, long).

123

Yii


, , - .
, .
Yii CNumberFormatter.
, , ,
numberFormatter.
CNumberFormatter :
format: (, $numberFormatter>format('#,##0.00',$number));
formatDecimal: ,
;
formatCurrency: ,
;
formatPercentage: ,
.


Yii (, Prado Smarty)
.
viewRenderer. CBaseController::renderFile,
.
:
, .
, .
, CPradoViewRenderer ,
, Prado.
, CPradoViewRenderer.

CPradoViewRenderer
CPradoViewRenderer :
return array(
'components'=>array(
,
'viewRenderer'=>array(
'class'=>'CPradoViewRenderer',
),
),
);
CPradoViewRenderer
PHP runtime. PHP- ,
. , CPradoViewRenderer
.
: , CPradoViewRenderer
, PHP ,
.
, CPradoViewRenderer.

124

Yii

PHP-
PHP- , . <%=
expression %> <?php echo expression ?>. <% statement %> <?php
statement ?>. :
<%= CHtml::textField($name,'value'); %>
<% foreach($models as $model): %>

<?php echo CHtml::textField($name,'value'); ?>
<?php foreach($models as $model): ?>


, . :
<com:WidgetClass property1=value1 property2=value2 >
//
</com:WidgetClass>
//
<com:WidgetClass property1=value1 property2=value2 />
WidgetClass .
, , PHP,
. :
<com:CCaptcha captchaAction="captcha" showRefreshButton={false} />

<?php $this->widget('CCaptcha', array(
'captchaAction'=>'captcha',
'showRefreshButton'=>false)); ?>

: showRefreshButton {false} "false"


, .


. :
<cache:fragmentID property1=value1 property2=value2 >
// ,
</cache:fragmentID >
fragmentID . -
. :
<cache:profile duration={3600}>
//
</cache:profile >

125

Yii

<?php if($this->cache('profile', array('duration'=>3600))): ?>
//
<?php $this->endCache(); endif; ?>


,
CBaseController::beginClip CBaseController::endClip. :
<clip:clipID>
//
</clip:clipID >
clipID .
:
<?php $this->beginClip('clipID'); ?>
//
<?php $this->endClip(); ?>


, .
. :
<!--
--->


1.1.2 , PHP
.
CViewRenderer::fileExtension , .php. , .tpl,
.tpl .
.php, , PHP.


,
, , .. Yii
, . ,
- (, ).

Yii . ,
CConsoleCommand.
. :
.
:
php entryScript.php CommandName Param0 Param1


126

Yii
, .
yiic webapp,
, protected/yiic.php.
:
defined('YII_DEBUG') or define('YII_DEBUG',true);
// Yii
require_once('path/to/yii/framework/yii.php');
//
$configFile='path/to/config/file.php';
Yii::createConsoleApplication($configFile)->run();


,
CConsoleApplication::commandPath. protected/commands.
CConsoleCommand.
XyzCommand, Xyz , .
, sitemap SitemapCommand.
.
: CConsoleApplication::commandMap,
.
(
) CConsoleCommand::run():
public function run($args) { ... }
$args , .


: 1.1.5.
. , sitemap
, , .
, ,
CController.
. actionXyz,
Xyz , . ,
actionIndex index.
, , :
php entryScript.php CommandName ActionName --Option1=Value1 --Option2=Value2 ...
- . xyz
$xyz . ,
:
class SitemapCommand extends CConsoleCommand
{

127

Yii

public function actionIndex($type, $limit=5) { ... }


public function actionInit() { ... }
}
actionIndex('News', 5):
php entryScript.php sitemap index --type=News --limit=5
// $limit
php entryScript.php sitemap index --type=News
// $limit .
// 'index' , .
php entryScript.php sitemap --type=News
//
php entryScript.php sitemap index --limit=5 --type=News
( --type --type=News),
true.
: , --type News -t News
.
, :
public function actionIndex(array $types) { ... }
:
php entryScript.php sitemap index --types=News --types=Article
, , actionIndex(array('News', 'Article')).


Yii::app() .
, -, . ,
db . , ,
- (
createConsoleApplication ).

yiic
yiic Yii-.
framework/yiic.php.
: -, ,
, CRUD, ,
..
, .
yiic webapp, Yii. protected: yiic yiic.bat
yiic, -.
protected/commands.
, . ,

128

Yii
, yiic shell.
protected/commands/shell.
1.1.1, , Yii,
.
YII_CONSOLE_COMMANDS, ,
. , yiic.


( XSS)
-. , , ,
JavaScript, VBScript, ActiveX, HTML Flash.
.
, - .
JavaScript- . , ,
.
XSS-, , ,
. , , HTML-.
, HTML .
Yii HTMLPurifier
CHtmlPurifier,
. .
CHtmlPurifier .
CHtmlPurifier :
<?php $this->beginWidget('CHtmlPurifier'); ?>

<?php $this->endWidget(); ?>


(CSRF) ,
- . ,
, img src, :
http://bank.example/?=10000&=.
cookie, ,
10000 . CSRF, ,
, .
, CSRF, : GET
. GET- . POST ,
, , .
Yii CSRF-, POST.
cookie POST.
, CSRF .
CHttpRequest :
return array(
'components'=>array(
'request'=>array(
'enableCsrfValidation'=>true,
),
),
);

129

Yii
CHtml::form HTML-.
, CSRF,
.

130

Yii

cookie
cookie , ID .
ID , , .
cookie:
SSL cookie .
cookie.
, cookie , ,
.
XSS, cookie.
cookie , .
Yii HMAC cookie.
cookie .
CHttpRequest :
return array(
'components'=>array(
'request'=>array(
'enableCookieValidation'=>true,
),
),
);
cookie, cookies,
$_COOKIES:
// cookie
$cookie=Yii::app()->request->cookies[$name];
$value=$cookie->value;

// cookie
$cookie=new CHttpCookie($name,$value);
Yii::app()->request->cookies[$name]=$cookie;

()
: yiic shell 1.1.2. ,
- Gii.
:
% cd WebRoot/testdrive
% protected/yiic shell
Yii Interactive Tool v1.1
Please type 'help' for help. Type 'exit' to quit.
>> model User tbl_user
generate models/User.php
generate fixtures/tbl_user.php
generate unit/UserTest.php
The following model classes are successfully generated:

131

Yii

User
If you have a 'db' database connection, you can test these models now with:
$model=User::model()->find();
print_r($model);
>> crud User
generate UserController.php
generate UserTest.php
mkdir D:/testdrive/protected/views/user
generate create.php
generate update.php
generate index.php
generate view.php
generate admin.php
generate _form.php
generate _view.php
Crud 'user' has been successfully created. You may access it via:
http://hostname/path/to/index.php?r=user
shell yiic
. : model User tbl_user crud User.
model User, tbl_user,
crud ,
CRUD.
: , , PDO
PDO, , , could not
find driver. yiic :
% php -c path/to/php.ini protected/yiic.php shell
path/to/php.ini PHP ini
, URL:
http://hostname/testdrive/index.php?r=user
tbl_user. ,
. Create User , ,
. .
Create. ,
.
, .
. ,

. (admin/admin),
:
http://hostname/testdrive/index.php?r=user/admin

132

Yii
. ,
. ,
. ,
.
!

133

Yii


artem.kruzhalin@gmail.com
1
http://yiiframework.ru

134

You might also like