Yii
Published: 13:26, Thursday 14 July 2011
Notes
What's this? See my article about Notes.
install:
install php5-memcache
workflow:
setup:
framework/yiic webapp webroot/projectname
still depends on the yii dir!
main view: protected/views/site/index.main
main layout: protected/views/layouts/index.main
setup db and gii in protected/config/main.php
generation/create models, crud:
?r=gii
(veery nice!)
url: ?r=route see [[#url management]]
the real work:
implement actions and views
configure action filters
internationalization
caching
tune up
testing: can be done for each step
basics:
application
Yii:app()
config:
protected/config/main.php
name, defaultController
application directory: protected contains .htaccess: deny from all
application component architecture:
can also be configured
CAssetManager
CAuthManager
CCache CMemCache
CClientScript (for js and css)
CPhpMessageSource
CDbConnection
CErrorHandler
CFormatter
CPhpMessageSource
CHttpRequest
CSecurityManager
CHttpSession
CStatePersister
CUrlManager
CWebUser
CThemeManager
controllers:
protected/controllers/
define inner paths like the wanted web paths
routing:
controllerID/actionID
moduleID/controllerID/actionID
activate: ?
actions:
actionX methods
action class:
in protected/controllers/post/UpdateAction.php
class UpdateAction extends CAction { public function run() { ..
in controller: public function actions() { return array('edit' => 'application.controllers.post.UpdateAction' ..
action parameter binding:
actionCreate($cat, $lang = 'en', array $sth)
$cat = (int)$cat;
filter:
before and after action
filterMethod($filterchain)
$filterchain->run() to continue
in protected/application/filters/
class BlaFilter extends CFilter { prot func preFilter($fc) { return true ...
in controller
public function filters() { return array(
'postOnly + edit, create',
array
'application.filters.PerformanceFilter - edit, create',
'unit' => 'second', // property
apply to: +
apply to all except: -
model:
types: form models, active record
view:
access controller with $this
display: $this->render(
layout view/main view
common to all
protected/views/layouts/main.php
don't print: renderPartial()
widget
self-contained ui
display: $this->widget('p.a.t.h'[, paramsarr])
with body: beginWidget('p.a.t.h') body endWidget()
custom
class BlaWidget extends CWidget
init() run()
system view
errorXXX (error404)
protected/views/system
component/components:
object written to a specification
getters/setters: getVarName, _varName
events:
pu fu onClicked($event)
$this->raiseEvent('onClicked', $event)
callback
$comp->onClicked = $callback;
array($object, 'methodName');
behavior. mixin pattern
$comp->attachBehavior(
then can execute methods of behavior to it!
module
has models, views, controllers, extensions, and modules
protected/modules/bla
BlaModule extends CWebModule
load:
in the app config 'modules' => array('bla', ...
or array('bla' => array(params ...
use:
Yii::app()->controller->module->bla;
access:
moduleID/controllerID/actionID
parentModuleID/childModuleID/controllerID/actionID
path alias
rootAlias.p.a.t.h
YiiBase::get/setPathOfAlias()
root aliases
system, zii, application, webroot, ext
and one for each module
import: Yii::import(pathalias)
Yii::$classMap= array('cname' => 'pathtocname.php' ...
conventions:
db: underscore, singular names, possibly prefixes
url management/urls
CUrlManager
in views: $url = $this->createUrl($route, $params);
get format: index.php?r=route&key=val
path format
index.php/route/key/val
there's a good format to uncomment in the config
config: 'components' => array(... 'urlManager' => array('urlFormat' => format, 'rules' => array('pattern' => 'route'
url generation: (?)
customized options
'pattern1'=>array('route1', 'urlSuffix'=>'.xml', 'caseSensitive'=>false)
array('route1', 'pattern'=>'pattern1', 'urlSuffix'=>'.xml', 'caseSensitive'=>false)
pattern, urlSuffix, caseSensitive, defaultParams, matchValue, verb, parsingOnly
named parameters
parameterized rules
hide index.php
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 = false
fake suffix
no thanks
custom url rule classes
authentication:
Yii::app()->user
CWebUser::isGuest
login, logout
CWebUser::checkAccess
extend CUserIdentity
implement authenticate
cookie based login strategy:
on login random key saved in cookie and on server
compare the keys
access control filter:
for all actions: in filters return also 'accessControl'
access rules
function accessRules()
params
actions, controllers
users (any: *, guest: ?, auth: @)
roles (uses rbac)
ips
verbs
expression
ex:
array('deny',
'actions'=>array('create', 'edit'),
'users'=>array('?'),
),
array('allow',
'actions'=>array('delete'),
'roles'=>array('admin'),
),
array('deny',
'actions'=>array('delete'),
['users'=>array('*'),]
),
authorization result:
fail: redirect to loginUrl (site/login)
role-based access control (rbac):
authorization item: operation, task, role
authorization hierarchy
if (Yii::app()->user->checkAccess('deletePost'))
auth manager:
config:
'authManager' => array(
'class' => 'CDbAuthManager',
'connectionID' => 'db',
),
access: $a = Yii::app()->authManager
$a = createOperation('createPost', 'create a post');
$bizRule='return Yii::app()->user->id==$params["post"]->authID;';
$t=$auth->createTask('updateOwnPost','update a post by author himself',$bizRule);
$t->addChild('updatePost');
$r = $a->createRole('author')
$r->addChild('reader')
$r->addChild('createPost')
$r->addChild('updateOwnPost')
businnes rules:
when to assign a role to a user
php code executed when checking
check access:
if (Yii:app()->user->checkAccess('createPost')
Yii::app()->user->checkAccess('updateOwnPost', array('post' => $post
default roles:
assigned to all users
'defaultRoles'=>array('authenticated', 'guest'),
$bizRule='return !Yii::app()->user->isGuest;';
$auth->createRole('authenticated', 'authenticated user', $bizRule);
$bizRule='return Yii::app()->user->isGuest;';
$auth->createRole('guest', 'guest user', $bizRule);
style:
#page.container
#header
#mainmenu
ul#yw0
.breadcrumbs
.container
#content
#footer
internationalization
Yii:t('app', 'string with {placeholder}'. array('{placeholder}' => $value
message source
CMessageSource
CPhpMessageSource
a php array
protected/messages/LocaleID/CategoryName.php
GGettextMessageSource: GNU Gettext
CDbMessageSource: translations stored in db
choice format
depending on number choose sing or plu
'expr1#message1|expr2#message2|...'
Yii::t('app', 'n==1#one book|n>1#many books', array(1)) or 1 directly
simpler: ('app', 'sing|plu', amt);
file translation:
CApplication::findLocalizedFile()
looks for one with same name under LocaleID dir
date and time formatting
CDateFormatter
app->dateFormatter->format('yyyy-MM-dd', $timestamp)
->formatDateTime
number formatting
Write a Comment
Name:
*
Email:
Website:
If you are human write 'w':
*
Title:
*
Your comment:
*
* These fields are mandatory.
© Copyright 2009-2011 Nicola Marcacci Rossi