SlideShare a Scribd company logo
1 of 42
Download to read offline
Yii - Next level PHP Framework


            Florian Fackler I 16. Februar 2012




                                                 © 2010 Mayflower GmbH
Donnerstag, 1. März 12
Yet Another PHP
                           Framework?


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

Donnerstag, 1. März 12
YES!!

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

Donnerstag, 1. März 12
My background



        I PHP-Developer since the late 1920s
        I 2009 I tried out about 10(!!) different PHP Frameworks:
          Akelos PHP Framework
          Cake PHP
          Codeigniter
          Kahona
          Recess
          Solar
          Symfony1
          Wombat
          Yii
          Zend Framework


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

Donnerstag, 1. März 12
Guess who won…




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

Donnerstag, 1. März 12
It’s rapid




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

Donnerstag, 1. März 12
It’s secure




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

Donnerstag, 1. März 12
It’s open for extensions
                         and 3rd party libs


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

Donnerstag, 1. März 12
It’s lean




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

Donnerstag, 1. März 12
It simply works!




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

Donnerstag, 1. März 12
Yii Background



        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 framework
          for 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




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

Donnerstag, 1. März 12
Highlights at a glance




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

Donnerstag, 1. März 12
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)




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

Donnerstag, 1. März 12
DB / Model




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

Donnerstag, 1. März 12
Yii Highlights: DB Active Record



        I Active Record: Lazy folk’s sql

       Create                                    Update                                       Delete
                                                 $post = Post::model()->findByPk(2);          $post = Post::model()->findByPk(2);
       $post = new Post;                         $post->title = ‘New title’;                  $post->delete();
      $post->title = 'sample post';              $post->save();
      $post->content = 'post body content';
      $post->save();


                                                           This is validated
                         This is validated


      $post=Post::model()->find(array(                    $post=Post::model()->find('postID=:postID', array(':postID'=>10));
          'select'=>'title',
          'condition'=>'postID=:postID',                  ---
          'params'=>array(':postID'=>10),
      ));                                                 $criteria=new CDbCriteria;
                                                          $criteria->select='title'; // only select the 'title' column
      ---                                                 $criteria->condition='postID=:postID';
                                                          $criteria->params=array(':postID'=>10);
      // find the first row using the SQL statement
      $post=Post::model()->findBySql($sql,$params);       $post=Post::model()->find($criteria); // $params is not needed




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

Donnerstag, 1. März 12
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
              createTable('tbl_user', array(         renameColumn('tbl_user', 'name', 'username')
                 'id'       => 'pk',
                 'username' => 'string NOT NULL',    dropColumn('tbl_user', 'location')
                 'location' => 'point',
              ), 'ENGINE=InnoDB')                    addColumn('tbl_user', 'email', 'string NOT NULL')

                                                     renameTable('tbl_users', 'tbl_user')




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

Donnerstag, 1. März 12
Yii Highlights: DAO



        I Data Access Objects (hardcore = true)
        I Built on top of PHP Data Objects (PDO)
        I DB query example:
              $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


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


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




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

Donnerstag, 1. März 12
Yii Highlights: DB Migrations



        I Example of query builder usage to migrate the DB schema
             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');
                   }
             }

        I Transaction support: Use safeUp() instead of up()
        I Applying a migration is as easy as 1 - 2 - 4:
              $   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



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

Donnerstag, 1. März 12
Yii Highlights: DB Relations



        I Add relations to your post model
              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)'),
                      );
                  }
              }




        I Making a query
              $post=Post::model()->findByPk(10);
              $author=$post->author;
                                                   Lazy


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




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

Donnerstag, 1. März 12
Yii Highlights: DB Scopes



        I Named scopes
              class Post extends CActiveRecord
              {
                   public function scopes()
                   {
                         return array(                            $posts=Post::model()->published()->recently()->findAll();

                              'published'=>array(
                                   'condition'=>'status=1',
                              ),
                              'recently'=>array(
                                   'order'=>'create_time DESC',
                                   'limit'=>5,
                              ),
                         );
                   }
              }




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

Donnerstag, 1. März 12
Yii Highlights: DB Scopes



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


        I How to display the last 3 posts?
              $posts=Post::model()->published()->recently(3)->findAll();




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

Donnerstag, 1. März 12
Yii Highlights: DB Scopes



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




        I Now every selects add’s the language condition automatically
              $contents=Content::model()->findAll();


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




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

Donnerstag, 1. März 12
Behaviors / Events




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

Donnerstag, 1. März 12
Yii Highlights: Defined hooks to extend your models



        I Every(!) CComponent calls hooks before/after certain actions
        I What is a hook?
             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.
        I Example:
              class Post extends CActiveRecord
              {
                public function beforeSave()
                {
                  if ($this->isNewRecord) {
                    $this->created = CDbExpression(‘NOW()’);
                  }
                  return parent::beforeSave();
                }
              }




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

Donnerstag, 1. März 12
Yii Highlights: Behaviors = to re-use your methods



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

              class Post extends CActiveRecord                           class CTimestampBehavior extends CActiveRecordBehavior
              {                                                          {
                public function behaviors(){                               public $createAttribute = ‘created_at’;
                  return array(
                     'timestamp' => array(                                   public function beforeSave($event)
                       'class' => 'ext.floWidgets.CTimestampBehavior',       {
                       'createAttribute' => 'create_time_attribute',           $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',
                    )
                 );
               }
             }


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

Donnerstag, 1. März 12
Yii Highlights: Custom events to extend your models



        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
                     - ...




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

Donnerstag, 1. März 12
Security




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

Donnerstag, 1. März 12
Yii Highlights: Security XSS (Cross Site Scripting)



        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>'); ?>




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

Donnerstag, 1. März 12
Yii Highlights: Security CSRF (Cross Site Request Forgery)



        I Protect your POST-Forms with an hidden token
        I Simply switch it on in the main configuration
              return array(
                  'components'=>array(
                      'request'=>array(
                          'enableCsrfValidation'=>true,
                      ),
                  ),
              );



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




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

Donnerstag, 1. März 12
Yii Highlights: Security Cookie Attack Prevention



        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;




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

Donnerstag, 1. März 12
Routing




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

Donnerstag, 1. März 12
Yii Highlights: Routing



        I Easy to configure
        I No voodoo needed
                                                                        class PostController extends CController
        I Examples:                                                     {
                                                                          public function read($id) {
              array(                                                          $post = Post::model()->findByPk($id);
                  'posts'=>'post/list',                                       if (! $post instanceof Post) {
                  'post/<id:d+>'=>'post/read',                                   throw new CHttpException(
                  'post/<year:d{4}>/<title>'=>'post/read',                           ‘Post not found’, 404
              )                                                                   );
                                                                              }
                                                                              $this->render(‘read’, array(‘post’ $post));
                                                                        }



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


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




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

Donnerstag, 1. März 12
Extensions / Modules




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

Donnerstag, 1. März 12
Yii Highlights: Extensions



        I Choose your extension out of ~ 750
                                                                                      neo4yii
          1    Auth (25)              facebook-opengraph
          2    Caching (16)
          3    Console (10)
          4    Database (65)                                                                          bad-words-filter
          5    Date and Time (14)                       s3assetmanager
          6    Error Handling (3)
          7    File System (23)       imgresizer
          8    Logging (19)                                                             timeago
          9    Mail (8)
          10   Networking (13)
          11   Security (10)                       detectmobilebrowser          yii-solr
          12   User Interface (312)
          13   Validation (47)
          14   Web Service (49)
          15   Others (175)
                                      phonenumbervalidator
                                                                                       ejabbersender




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

Donnerstag, 1. März 12
Yii Highlights: Modules



        I A module is like a small, independent MVC in your MVC
             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

        I How to use it?
               return array(
                   ......
                   'modules'=>array(
                       'forum'=>array(
                           'postPerPage'=>20,
                       ),
                   ),
               );



        I Can modules be nested? Sure!


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

Donnerstag, 1. März 12
Widgets




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

Donnerstag, 1. März 12
Yii Highlights: Widgets



        I Widget surrounding Content (e.g. Autolinking, BadWord-Filter,
          HTML-Purification, ...)
            <?php $this->beginWidget('ext.xyz.XyzClass', array(
                'property1'=>'value1',
                'property2'=>'value2')); ?>

            ...body content of the widget...

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




        I “Stand alone” Widget (e.g. Language-Selector, CForm, ...)
              <?php $this->widget('ext.xyz.XyzClass', array(
                  'property1'=>'value1',
                  'property2'=>'value2')); ?>




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

Donnerstag, 1. März 12
Console




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

Donnerstag, 1. März 12
Yii Highlights: Console



        I Create console actions for cronjobs
              class S3ManagerCommand extends CConsoleCommand
              {
                  public function actionCleanUpBucket($bucket)
                  {
                      echo "Cleaning up S3 bucket $bucketn";
                      ...
                  }
              }


        I Show all console commands:
              $ ./protected/yiic
                                                             Create a new yii web application sekelton
              -   webapp
              -   migration
              -
              -
                  s3manager
                  usermanager
                                                                 Yii shell to create new model/
              -   migrate                                        module/controller skeletons
              -   shell
              -   message
              -   ...

                                                            Automatically grep your views for i18n texts




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

Donnerstag, 1. März 12
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
             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');
                 }




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

Donnerstag, 1. März 12
Vielen Dank für Ihre Aufmerksamkeit!




                Kontakt   Florian Fackler              Twitter: https://twitter.com/#!/mintao
                          florian.fackler@mayflower.de
                          +49 89 242054-1  176

                          Mayflower GmbH
                          Mannhardtstr. 6
                          80538 München




                                                                                    © 2010 Mayflower GmbH
Donnerstag, 1. März 12
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/download
  Yii http://www.yiiframework.com/
  Zend Framework http://framework.zend.com/

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




Donnerstag, 1. März 12

More Related Content

Viewers also liked

Asitein 15 minutes with yii
Asitein 15 minutes with yiiAsitein 15 minutes with yii
Asitein 15 minutes with yiiAdamPSB
 
Mis Bandas Favoitas
Mis Bandas FavoitasMis Bandas Favoitas
Mis Bandas FavoitasJose Monter
 
Інформатика. Другий рік – єдиний курс. 10 клас.
Інформатика. Другий рік – єдиний курс. 10 клас.Інформатика. Другий рік – єдиний курс. 10 клас.
Інформатика. Другий рік – єдиний курс. 10 клас.StAlKeRoV
 
8 клас 30 урок. Величини (змінні і константи), їхні властивості.
8 клас 30 урок. Величини (змінні і константи), їхні властивості.8 клас 30 урок. Величини (змінні і константи), їхні властивості.
8 клас 30 урок. Величини (змінні і константи), їхні властивості.StAlKeRoV
 
8 клас 38 урок. Алгоритми з розгалуженнями для опрацювання величин.
8 клас 38 урок. Алгоритми з розгалуженнями для опрацювання величин.8 клас 38 урок. Алгоритми з розгалуженнями для опрацювання величин.
8 клас 38 урок. Алгоритми з розгалуженнями для опрацювання величин.StAlKeRoV
 
2 клас 23 урок. Сервіси для перегляду зображень картин художників. Віртуаль...
2 клас 23  урок.  Сервіси для перегляду зображень картин художників. Віртуаль...2 клас 23  урок.  Сервіси для перегляду зображень картин художників. Віртуаль...
2 клас 23 урок. Сервіси для перегляду зображень картин художників. Віртуаль...StAlKeRoV
 
Trp yogya paes ageng
Trp yogya paes agengTrp yogya paes ageng
Trp yogya paes agengLkp Adi Tiara
 

Viewers also liked (8)

Asitein 15 minutes with yii
Asitein 15 minutes with yiiAsitein 15 minutes with yii
Asitein 15 minutes with yii
 
Mis Bandas Favoitas
Mis Bandas FavoitasMis Bandas Favoitas
Mis Bandas Favoitas
 
Epe 414
Epe 414Epe 414
Epe 414
 
Інформатика. Другий рік – єдиний курс. 10 клас.
Інформатика. Другий рік – єдиний курс. 10 клас.Інформатика. Другий рік – єдиний курс. 10 клас.
Інформатика. Другий рік – єдиний курс. 10 клас.
 
8 клас 30 урок. Величини (змінні і константи), їхні властивості.
8 клас 30 урок. Величини (змінні і константи), їхні властивості.8 клас 30 урок. Величини (змінні і константи), їхні властивості.
8 клас 30 урок. Величини (змінні і константи), їхні властивості.
 
8 клас 38 урок. Алгоритми з розгалуженнями для опрацювання величин.
8 клас 38 урок. Алгоритми з розгалуженнями для опрацювання величин.8 клас 38 урок. Алгоритми з розгалуженнями для опрацювання величин.
8 клас 38 урок. Алгоритми з розгалуженнями для опрацювання величин.
 
2 клас 23 урок. Сервіси для перегляду зображень картин художників. Віртуаль...
2 клас 23  урок.  Сервіси для перегляду зображень картин художників. Віртуаль...2 клас 23  урок.  Сервіси для перегляду зображень картин художників. Віртуаль...
2 клас 23 урок. Сервіси для перегляду зображень картин художників. Віртуаль...
 
Trp yogya paes ageng
Trp yogya paes agengTrp yogya paes ageng
Trp yogya paes ageng
 

Similar to Yii Next Level

Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolmentRajib Ahmed
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
How to insert json data into my sql using php
How to insert json data into my sql using phpHow to insert json data into my sql using php
How to insert json data into my sql using phpTrà Minh
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroChristopher Pecoraro
 
Yii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toYii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toAlexander Makarov
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHPRohan Sharma
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comtutorialsruby
 
Oop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.comOop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.comayandoesnotemail
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan Wage
 
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdfHow to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdfBe Problem Solver
 
Part 2
Part 2Part 2
Part 2A VD
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersVineet Kumar Saini
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Nelson Gomes
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 

Similar to Yii Next Level (20)

Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolment
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
How to insert json data into my sql using php
How to insert json data into my sql using phpHow to insert json data into my sql using php
How to insert json data into my sql using php
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
 
Yii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toYii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading to
 
Oops in php
Oops in phpOops in php
Oops in php
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 
Building Custom PHP Extensions
Building Custom PHP ExtensionsBuilding Custom PHP Extensions
Building Custom PHP Extensions
 
Oop in php tutorial
Oop in php tutorialOop in php tutorial
Oop in php tutorial
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.com
 
Oop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.comOop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.com
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdfHow to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
 
Part 2
Part 2Part 2
Part 2
 
Oop's in php
Oop's in php Oop's in php
Oop's in php
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and Answers
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 

Recently uploaded

Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.raviapr7
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...Nguyen Thanh Tu Collection
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...raviapr7
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxraviapr7
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17Celine George
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptxSandy Millin
 
General views of Histopathology and step
General views of Histopathology and stepGeneral views of Histopathology and step
General views of Histopathology and stepobaje godwin sunday
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17Celine George
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17Celine George
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.EnglishCEIPdeSigeiro
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfYu Kanazawa / Osaka University
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxMYDA ANGELICA SUAN
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphNetziValdelomar1
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesMohammad Hassany
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice documentXsasf Sfdfasd
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxKatherine Villaluna
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 

Recently uploaded (20)

Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptx
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
 
General views of Histopathology and step
General views of Histopathology and stepGeneral views of Histopathology and step
General views of Histopathology and step
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptx
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a Paragraph
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming Classes
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice document
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptx
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 

Yii Next Level

  • 1. Yii - Next level PHP Framework Florian Fackler I 16. Februar 2012 © 2010 Mayflower GmbH Donnerstag, 1. März 12
  • 2. Yet Another PHP Framework? Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 2 Donnerstag, 1. März 12
  • 3. YES!! Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 3 Donnerstag, 1. März 12
  • 4. My background I PHP-Developer since the late 1920s I 2009 I tried out about 10(!!) different PHP Frameworks: Akelos PHP Framework Cake PHP Codeigniter Kahona Recess Solar Symfony1 Wombat Yii Zend Framework Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 4 Donnerstag, 1. März 12
  • 5. Guess who won… Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 5 Donnerstag, 1. März 12
  • 6. It’s rapid Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 6 Donnerstag, 1. März 12
  • 7. It’s secure Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 7 Donnerstag, 1. März 12
  • 8. It’s open for extensions and 3rd party libs Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 8 Donnerstag, 1. März 12
  • 9. It’s lean Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 9 Donnerstag, 1. März 12
  • 10. It simply works! Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 10 Donnerstag, 1. März 12
  • 11. Yii Background 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 framework for 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 Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 11 Donnerstag, 1. März 12
  • 12. Highlights at a glance Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 12 Donnerstag, 1. März 12
  • 13. 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) Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 13 Donnerstag, 1. März 12
  • 14. DB / Model Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 14 Donnerstag, 1. März 12
  • 15. Yii Highlights: DB Active Record I Active Record: Lazy folk’s sql Create Update Delete $post = Post::model()->findByPk(2); $post = Post::model()->findByPk(2); $post = new Post; $post->title = ‘New title’; $post->delete(); $post->title = 'sample post'; $post->save(); $post->content = 'post body content'; $post->save(); This is validated This is validated $post=Post::model()->find(array( $post=Post::model()->find('postID=:postID', array(':postID'=>10)); 'select'=>'title', 'condition'=>'postID=:postID', --- 'params'=>array(':postID'=>10), )); $criteria=new CDbCriteria; $criteria->select='title'; // only select the 'title' column --- $criteria->condition='postID=:postID'; $criteria->params=array(':postID'=>10); // find the first row using the SQL statement $post=Post::model()->findBySql($sql,$params); $post=Post::model()->find($criteria); // $params is not needed Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 15 Donnerstag, 1. März 12
  • 16. 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 createTable('tbl_user', array( renameColumn('tbl_user', 'name', 'username') 'id' => 'pk', 'username' => 'string NOT NULL', dropColumn('tbl_user', 'location') 'location' => 'point', ), 'ENGINE=InnoDB') addColumn('tbl_user', 'email', 'string NOT NULL') renameTable('tbl_users', 'tbl_user') Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 16 Donnerstag, 1. März 12
  • 17. Yii Highlights: DAO I Data Access Objects (hardcore = true) I Built on top of PHP Data Objects (PDO) I DB query example: $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 I Binding parameters $sql="INSERT INTO tbl_user (username, email) VALUES(:username,:email)"; $command=$connection->createCommand($sql); $command->bindParam(":username", $username, PDO::PARAM_STR); I Binding columns $sql="SELECT username, email FROM tbl_user"; $dataReader=$connection->createCommand($sql)->query(); $dataReader->bindColumn(1,$username); $dataReader->bindColumn(2,$email); while($dataReader->read()!==false) {...} Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 17 Donnerstag, 1. März 12
  • 18. Yii Highlights: DB Migrations I Example of query builder usage to migrate the DB schema 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'); } } I Transaction support: Use safeUp() instead of up() I Applying a migration is as easy as 1 - 2 - 4: $ 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 Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 18 Donnerstag, 1. März 12
  • 19. Yii Highlights: DB Relations I Add relations to your post model 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)'), ); } } I Making a query $post=Post::model()->findByPk(10); $author=$post->author; Lazy EAGER $posts=Post::model()->with('author')->findAll(); $posts=Post::model()->with('author.username, author.email','categories')->findAll(); Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 19 Donnerstag, 1. März 12
  • 20. Yii Highlights: DB Scopes I Named scopes class Post extends CActiveRecord { public function scopes() { return array( $posts=Post::model()->published()->recently()->findAll(); 'published'=>array( 'condition'=>'status=1', ), 'recently'=>array( 'order'=>'create_time DESC', 'limit'=>5, ), ); } } Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 20 Donnerstag, 1. März 12
  • 21. Yii Highlights: DB Scopes I Parameterized names scope public function recently($limit=5) { $this->getDbCriteria()->mergeWith(array( 'order'=>'create_time DESC', 'limit'=>$limit, )); return $this; } I How to display the last 3 posts? $posts=Post::model()->published()->recently(3)->findAll(); Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 21 Donnerstag, 1. März 12
  • 22. Yii Highlights: DB Scopes I Default Scope class Content extends CActiveRecord { public function defaultScope() { return array( 'condition'=>"language='".Yii::app()->language."'", ); } } I Now every selects add’s the language condition automatically $contents=Content::model()->findAll(); => SELECT * FROM `tbl_content` WHERE `language` = ‘en’; Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 22 Donnerstag, 1. März 12
  • 23. Behaviors / Events Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 23 Donnerstag, 1. März 12
  • 24. Yii Highlights: Defined hooks to extend your models I Every(!) CComponent calls hooks before/after certain actions I What is a hook? 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. I Example: class Post extends CActiveRecord { public function beforeSave() { if ($this->isNewRecord) { $this->created = CDbExpression(‘NOW()’); } return parent::beforeSave(); } } Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 24 Donnerstag, 1. März 12
  • 25. Yii Highlights: Behaviors = to re-use your methods I Every(!) CComponent can be enriched by behaviors listening to hooks or custom events I Example: class Post extends CActiveRecord class CTimestampBehavior extends CActiveRecordBehavior { { public function behaviors(){ public $createAttribute = ‘created_at’; return array( 'timestamp' => array( public function beforeSave($event) 'class' => 'ext.floWidgets.CTimestampBehavior', { 'createAttribute' => 'create_time_attribute', $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', ) ); } } Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 25 Donnerstag, 1. März 12
  • 26. Yii Highlights: Custom events to extend your models 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 - ... Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 26 Donnerstag, 1. März 12
  • 27. Security Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 27 Donnerstag, 1. März 12
  • 28. Yii Highlights: Security XSS (Cross Site Scripting) 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>'); ?> Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 28 Donnerstag, 1. März 12
  • 29. Yii Highlights: Security CSRF (Cross Site Request Forgery) I Protect your POST-Forms with an hidden token I Simply switch it on in the main configuration return array( 'components'=>array( 'request'=>array( 'enableCsrfValidation'=>true, ), ), ); I Important: Never use GET-Requests to modify/delete data Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 29 Donnerstag, 1. März 12
  • 30. Yii Highlights: Security Cookie Attack Prevention 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; Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 30 Donnerstag, 1. März 12
  • 31. Routing Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 31 Donnerstag, 1. März 12
  • 32. Yii Highlights: Routing I Easy to configure I No voodoo needed class PostController extends CController I Examples: { public function read($id) { array( $post = Post::model()->findByPk($id); 'posts'=>'post/list', if (! $post instanceof Post) { 'post/<id:d+>'=>'post/read', throw new CHttpException( 'post/<year:d{4}>/<title>'=>'post/read', ‘Post not found’, 404 ) ); } $this->render(‘read’, array(‘post’ $post)); } I Parameterizing Hostnames array( 'http://<user:w+>.example.com/<lang:w+>/profile' => 'user/profile', ) I Creating a url echo CHtml::link(‘Show post’, array(‘post/read’, ‘id’ => $post->id)); Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 32 Donnerstag, 1. März 12
  • 33. Extensions / Modules Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 33 Donnerstag, 1. März 12
  • 34. Yii Highlights: Extensions I Choose your extension out of ~ 750 neo4yii 1 Auth (25) facebook-opengraph 2 Caching (16) 3 Console (10) 4 Database (65) bad-words-filter 5 Date and Time (14) s3assetmanager 6 Error Handling (3) 7 File System (23) imgresizer 8 Logging (19) timeago 9 Mail (8) 10 Networking (13) 11 Security (10) detectmobilebrowser yii-solr 12 User Interface (312) 13 Validation (47) 14 Web Service (49) 15 Others (175) phonenumbervalidator ejabbersender Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 34 Donnerstag, 1. März 12
  • 35. Yii Highlights: Modules I A module is like a small, independent MVC in your MVC 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 I How to use it? return array( ...... 'modules'=>array( 'forum'=>array( 'postPerPage'=>20, ), ), ); I Can modules be nested? Sure! Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 35 Donnerstag, 1. März 12
  • 36. Widgets Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 36 Donnerstag, 1. März 12
  • 37. Yii Highlights: Widgets I Widget surrounding Content (e.g. Autolinking, BadWord-Filter, HTML-Purification, ...) <?php $this->beginWidget('ext.xyz.XyzClass', array( 'property1'=>'value1', 'property2'=>'value2')); ?> ...body content of the widget... <?php $this->endWidget(); ?> I “Stand alone” Widget (e.g. Language-Selector, CForm, ...) <?php $this->widget('ext.xyz.XyzClass', array( 'property1'=>'value1', 'property2'=>'value2')); ?> Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 37 Donnerstag, 1. März 12
  • 38. Console Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 38 Donnerstag, 1. März 12
  • 39. Yii Highlights: Console I Create console actions for cronjobs class S3ManagerCommand extends CConsoleCommand { public function actionCleanUpBucket($bucket) { echo "Cleaning up S3 bucket $bucketn"; ... } } I Show all console commands: $ ./protected/yiic Create a new yii web application sekelton - webapp - migration - - s3manager usermanager Yii shell to create new model/ - migrate module/controller skeletons - shell - message - ... Automatically grep your views for i18n texts Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 39 Donnerstag, 1. März 12
  • 40. 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 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'); } Yii - Next level PHP Framework I Mayflower GmbH I 16. Februar 2012 I 40 Donnerstag, 1. März 12
  • 41. Vielen Dank für Ihre Aufmerksamkeit! Kontakt Florian Fackler Twitter: https://twitter.com/#!/mintao florian.fackler@mayflower.de +49 89 242054-1 176 Mayflower GmbH Mannhardtstr. 6 80538 München © 2010 Mayflower GmbH Donnerstag, 1. März 12
  • 42. 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/download Yii http://www.yiiframework.com/ Zend Framework http://framework.zend.com/ Secure Cookie Protocol http://www.cse.msu.edu/~alexliu/publications/Cookie/cookie.pdf Yii Facebook Page https://www.facebook.com/groups/61355672149/ Donnerstag, 1. März 12