Yii Next Level

42
© 2010 Mayflower GmbH Florian Fackler I 16. Februar 2012 Yii - Next level PHP Framework

description

From internet ^^ i like this this is not my mine

Transcript of Yii Next Level

Page 1: Yii Next Level

© 2010 Mayflower GmbH

Florian Fackler I 16. Februar 2012

Yii - Next level PHP Framework

Donnerstag, 1. März 12

Page 2: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yet Another PHP Framework?

2

Donnerstag, 1. März 12

Page 3: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

YES!!

3

Donnerstag, 1. März 12

Page 4: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

My background

I PHP-Developer since the late 1920s

I 2009 I tried out about 10(!!) different PHP Frameworks:Akelos PHP Framework Cake PHPCodeigniterKahonaRecessSolarSymfony1WombatYiiZend Framework

4

Donnerstag, 1. März 12

Page 5: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 5

Guess who won…

Donnerstag, 1. März 12

Page 6: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

It’s rapid

6

Donnerstag, 1. März 12

Page 7: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

It’s secure

7

Donnerstag, 1. März 12

Page 8: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

It’s open for extensions and 3rd party libs

8

Donnerstag, 1. März 12

Page 9: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

It’s lean

9

Donnerstag, 1. März 12

Page 10: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

It simply works!

10

Donnerstag, 1. März 12

Page 11: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Background

11

I Qiang Xue (Washington DC, USA) startet Yii in 2008

I Former developer of Prado Framework (PRADO is a component-based and event-driven programming frameworkfor developing Web applications in PHP 5)

I What does Yii stand for? Is it chinese? No,it’s an acronym for Yes, it is! (Is it fast? ... Is it secure? ... Is it professional? ... Is it right for my next project? ... Yes, it is! :))

I Team: 7 Core developers and an very active community

I Facebook page, Google Group, github.com

Donnerstag, 1. März 12

Page 12: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 12

Highlights at a glance

Donnerstag, 1. März 12

Page 13: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights

I Database Access Objects (DAO), Query Builder, AR

I Migration system to step up and down your migrations

I Easy Console Applications

I Routing you always wanted to have

I Flexibility with Widgets (= View Helpers++)

I Expandable with Extensions / Wrappers for 3rd party libs

I Highly secure

I Scaffolding

I => Your code will be CLEAN, LEAN & REUSABLE(Events, Behaviors, Hooks, Modules, Action-Controllers e.g. Upload-Controller)

13

Donnerstag, 1. März 12

Page 14: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 14

DB / Model

Donnerstag, 1. März 12

Page 15: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights: DB Active Record

I Active Record: Lazy folk’s sql

15

Create

$post = new Post;$post->title = 'sample post';$post->content = 'post body content';$post->save();

Delete$post = Post::model()->findByPk(2);$post->delete();

Update$post = Post::model()->findByPk(2);$post->title = ‘New title’;$post->save();

This is validatedThis is validated

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

---

// find the first row using the SQL statement$post=Post::model()->findBySql($sql,$params);

$post=Post::model()->find('postID=:postID', array(':postID'=>10));

---

$criteria=new CDbCriteria;$criteria->select='title'; // only select the 'title' column$criteria->condition='postID=:postID';$criteria->params=array(':postID'=>10);

$post=Post::model()->find($criteria); // $params is not needed

Donnerstag, 1. März 12

Page 16: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights: DB Query Builder

I Query Builder (magicOff = true)$user = Yii::app()->db->createCommand()

->select('id, username, profile') ->from('tbl_user u') ->join('tbl_profile p', 'u.id=p.user_id') ->where('id=:id', array(':id'=>$id)) ->queryRow()

I Native SQL commands

I Parameter binding => Secure queries

I Multiple syntaxes possible. Choose your preferred syntax

I No overhead

16

renameColumn('tbl_user', 'name', 'username')

dropColumn('tbl_user', 'location')

addColumn('tbl_user', 'email', 'string NOT NULL')

renameTable('tbl_users', 'tbl_user')

createTable('tbl_user', array( 'id' => 'pk', 'username' => 'string NOT NULL', 'location' => 'point',), 'ENGINE=InnoDB')

Donnerstag, 1. März 12

Page 17: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights: DAO

I Data Access Objects (hardcore = true)

I Built on top of PHP Data Objects (PDO)

I DB query example:

I Binding parameters

I Binding columns

17

$sql = ‘SELECT * FROM users’;Yii::app()->db->createCommand($sql);...$rowCount=$command->execute(); // execute the non-query SQL$dataReader=$command->query(); // execute a query SQL$rows=$command->queryAll(); // query and return all rows of result$row=$command->queryRow(); // query and return the first row of result$column=$command->queryColumn(); // query and return the first column of result$value=$command->queryScalar(); // query and return the first field in the first row

$sql="INSERT INTO tbl_user (username, email) VALUES(:username,:email)";$command=$connection->createCommand($sql);$command->bindParam(":username", $username, PDO::PARAM_STR);

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

Donnerstag, 1. März 12

Page 18: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Example of query builder usage to migrate the DB schema

I Transaction support: Use safeUp() instead of up()

I Applying a migration is as easy as 1 - 2 - 4:

18

Yii Highlights: DB Migrations

class m101129_185401_create_news_table extends CDbMigration{ public function up() { $this->createTable('tbl_news', array( 'id' => 'pk', 'title' => 'string NOT NULL', 'content' => 'text', )); } public function down() { $this->dropTable('tbl_news'); }}

$ yiic migrate$ yiic migrate up 3$ yiic migrate to 101129_185401$ yiic migrate down [step]$ yiic migrate redo [step]$ yiic migrate history [limit]$ yiic migrate new [limit]$ yiic migrate mark 101129_185401

Donnerstag, 1. März 12

Page 19: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Add relations to your post model

I Making a query

19

Yii Highlights: DB Relations

class Post extends CActiveRecord{ public function relations() { return array( 'rating' => array(self::HAS_ONE, 'Rating', 'post_id'), 'comments' => array(self::HAS_MANY, 'Comment', 'post_id', 'order'=>'create_time DESC'), 'author' => array(self::BELONGS_TO, 'User', 'id'), 'categories' => array(self::MANY_MANY, 'Category', 'tbl_post_category(post_id, category_id)'), ); }}

$post=Post::model()->findByPk(10);$author=$post->author; Lazy

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

EAGER

Donnerstag, 1. März 12

Page 20: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Named scopes

20

Yii Highlights: DB Scopes

class Post extends CActiveRecord{ public function scopes() { return array( 'published'=>array( 'condition'=>'status=1', ), 'recently'=>array( 'order'=>'create_time DESC', 'limit'=>5, ), ); }}

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

Donnerstag, 1. März 12

Page 21: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Parameterized names scope

I How to display the last 3 posts?

21

Yii Highlights: DB Scopes

public function recently($limit=5){ $this->getDbCriteria()->mergeWith(array( 'order'=>'create_time DESC', 'limit'=>$limit, )); return $this;}

$posts=Post::model()->published()->recently(3)->findAll();

Donnerstag, 1. März 12

Page 22: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Default Scope

I Now every selects add’s the language condition automatically

22

Yii Highlights: DB Scopes

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

$contents=Content::model()->findAll();

=> SELECT * FROM `tbl_content` WHERE `language` = ‘en’;

Donnerstag, 1. März 12

Page 23: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Behaviors / Events

23

Donnerstag, 1. März 12

Page 24: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Every(!) CComponent calls hooks before/after certain actions

I What is a hook?

I Example:

24

beforeValidate and afterValidate: these are invoked before and after validation is performed.beforeSave and afterSave: these are invoked before and after saving an AR instance.beforeDelete and afterDelete: these are invoked before and after an AR instance is deleted.afterConstruct: this is invoked for every AR instance created using the new operator.beforeFind: this is invoked before an AR finder is used to perform a query (e.g. find(), findAll()).afterFind: this is invoked after every AR instance created as a result of query.

Yii Highlights: Defined hooks to extend your models

class Post extends CActiveRecord{ public function beforeSave() { if ($this->isNewRecord) { $this->created = CDbExpression(‘NOW()’); } return parent::beforeSave(); }}

Donnerstag, 1. März 12

Page 25: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Every(!) CComponent can be enriched by behaviors listening to hooks or custom events

I Example:

25

Yii Highlights: Behaviors = to re-use your methods

class Post extends CActiveRecord{ public function behaviors(){ return array( 'timestamp' => array( 'class' => 'ext.floWidgets.CTimestampBehavior', 'createAttribute' => 'create_time_attribute', ) ); }}

class CTimestampBehavior extends CActiveRecordBehavior{ public $createAttribute = ‘created_at’;

public function beforeSave($event) { $model = $event->sender; $model->$createAttribute = CDbExpression(‘NOW()’); }}

class Comment extends CActiveRecord{ public function behaviors(){ return array( 'timestamp' => array( 'class' => 'ext.floWidgets.CTimestampBehavior', 'createAttribute' => 'create_time_attribute', ) ); }}

Donnerstag, 1. März 12

Page 26: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Publish/Subscribe => One event causes unlimited actions and does’t event know about it

I CAUTION! With big power comes big responsibility!!

I Example:

•New User subscribed- mail to admin

- welcome mail to user

- create new invoice

- ...

26

Yii Highlights: Custom events to extend your models

Donnerstag, 1. März 12

Page 27: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 27

Security

Donnerstag, 1. März 12

Page 28: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Display insecure user content<?php $this->beginWidget('CHtmlPurifier'); ?>

<?php echo $post->unsecureBody ?> <?php $this->endWidget(); ?>

I ... or simply escape a single string with the included “encode” function<?php echo CHtml::encode('<script>transferUserdata();</script>'); ?>

28

Yii Highlights: Security XSS (Cross Site Scripting)

Donnerstag, 1. März 12

Page 29: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I Protect your POST-Forms with an hidden token

I Simply switch it on in the main configuration

I Important: Never use GET-Requests to modify/delete data

29

Yii Highlights: Security CSRF (Cross Site Request Forgery)

return array( 'components'=>array( 'request'=>array( 'enableCsrfValidation'=>true, ), ),);

Donnerstag, 1. März 12

Page 30: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

I HMAC check for the cookie (Keyed-Hash Message Authentication Code)// retrieve the cookie with the specified name

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

30

Yii Highlights: Security Cookie Attack Prevention

Donnerstag, 1. März 12

Page 31: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Routing

31

Donnerstag, 1. März 12

Page 32: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights: Routing

32

I Easy to configure

I No voodoo needed

I Examples:

I Parameterizing Hostnames

I Creating a url

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

class PostController extends CController{ public function read($id) { $post = Post::model()->findByPk($id); if (! $post instanceof Post) { throw new CHttpException( ‘Post not found’, 404 ); } $this->render(‘read’, array(‘post’ $post));}

array( 'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile',)

echo CHtml::link(‘Show post’, array(‘post/read’, ‘id’ => $post->id));

Donnerstag, 1. März 12

Page 33: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Extensions / Modules

33

Donnerstag, 1. März 12

Page 34: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights: Extensions

34

I Choose your extension out of ~ 750

1 Auth (25)2 Caching (16)3 Console (10)4 Database (65)5 Date and Time (14)6 Error Handling (3)7 File System (23)8 Logging (19)9 Mail (8)10 Networking (13)11 Security (10)12 User Interface (312)13 Validation (47)14 Web Service (49)15 Others (175)

s3assetmanager

detectmobilebrowser

neo4yiifacebook-opengraph

timeago

yii-solr

ejabbersenderphonenumbervalidator

imgresizer

bad-words-filter

Donnerstag, 1. März 12

Page 35: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights: Modules

35

I A module is like a small, independent MVC in your MVC

I How to use it?

I Can modules be nested? Sure!

forum/ ForumModule.php the module class file components/ containing reusable user components views/ containing view files for widgets controllers/ containing controller class files DefaultController.php the default controller class file extensions/ containing third-party extensions models/ containing model class files views/ containing controller view and layout files layouts/ containing layout view files default/ containing view files for DefaultController index.php the index view file

return array( ...... 'modules'=>array( 'forum'=>array( 'postPerPage'=>20, ), ),);

Donnerstag, 1. März 12

Page 36: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Widgets

36

Donnerstag, 1. März 12

Page 37: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights: Widgets

37

I Widget surrounding Content (e.g. Autolinking, BadWord-Filter, HTML-Purification, ...)

I “Stand alone” Widget (e.g. Language-Selector, CForm, ...)

<?php $this->beginWidget('ext.xyz.XyzClass', array( 'property1'=>'value1', 'property2'=>'value2')); ?> ...body content of the widget... <?php $this->endWidget(); ?>

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

Donnerstag, 1. März 12

Page 38: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Console

38

Donnerstag, 1. März 12

Page 39: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights: Console

39

I Create console actions for cronjobs

I Show all console commands:

class S3ManagerCommand extends CConsoleCommand{ public function actionCleanUpBucket($bucket) { echo "Cleaning up S3 bucket $bucket\n"; ... }}

$ ./protected/yiic

- webapp- migration- s3manager- usermanager- migrate- shell- message- ...

Automatically grep your views for i18n texts

Yii shell to create new model/module/controller skeletons

Create a new yii web application sekelton

Donnerstag, 1. März 12

Page 40: Yii Next Level

Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I

Yii Highlights: ..Even more advantages

I i18n ... easy peasy 1 - 2 - 3 (translate phrases or override whole views)

I Themes (override some/all views with a special version e.g.. mobile)

I ACL (Filters, authentication per method, verb, ip, ...)

I Gii module (Web interface for creating controllers, models, modules)

I Caching (Data-, Fragment-, Page-, Dynamic caching)

I PHP-Unit / Selenium

40

public function testShow() { $this->open('post/1'); // verify the sample post title exists $this->assertTextPresent($this->posts['sample1']['title']); // verify comment form exists $this->assertTextPresent('Leave a Comment'); }

Donnerstag, 1. März 12

Page 41: Yii Next Level

Vielen Dank für Ihre Aufmerksamkeit!

© 2010 Mayflower GmbH

Kontakt Florian [email protected]+49 89 242054-1176

Mayflower GmbHMannhardtstr. 680538 München

Twitter: https://twitter.com/#!/mintao

Donnerstag, 1. März 12

Page 42: Yii Next Level

Sources

Akelos Framework Akelos PHP Framework Web Site Cake PHP http://cakephp.org/Codeigniter http://codeigniter.com/Kohana http://kohanaframework.org/Recess Framework http://www.recessframework.org/Solar http://solarphp.com/ Symfony http://www.symfony-project.org/Wombat http://wombat.exit0.net/downloadYii http://www.yiiframework.com/Zend Framework http://framework.zend.com/

Secure Cookie Protocol http://www.cse.msu.edu/~alexliu/publications/Cookie/cookie.pdfYii Facebook Page https://www.facebook.com/groups/61355672149/

Donnerstag, 1. März 12