SlideShare uma empresa Scribd logo
1 de 28
Introduction to
Jason Ragsdale
March 10th, 2009
Dallas PHP MySQL Users Group
Framework Features
• MVC design pattern                • Theming


• DAO and Active Record             • Web services


• jQuery-based JavaScript support   • Console applications


• I18N and L10N                     • Authentication and authorization


• Page, fragment and data caching   • Web 2.0 widgets


• Error handling and logging        • Form input and validation
Yii basics - MVC Overview
 Static structure of Yii application   A typical workflow of Yii application
Yii basics - Entry Script
 • Entry script is the bootstrap PHP script that handles user requests initially. It
   is the only PHP script that end users can directly request to execute.


// remove the following line when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);

// include Yii bootstrap file
require_once('path/to/yii/framework/yii.php');

// create application instance and run
$configFile='path/to/config/file.php';
Yii::createWebApplication($configFile)->run();
Yii basics - Application

 • Application represents the execution context of request processing. Its main
   task is to resolve the user request and dispatch it to an appropriate controller
   for further processing. It also serves as the central place for keeping
   application-level configurations. For this reason, application is also called
   front-controller.

 • Application Configuration

array(
   'name'=>'Yii Framework',
   'defaultController'=>'site',
)
Yii basics - Controller

 • A controller is an instance of CController or its child class. It is created by
   application when the user requests for it. When a controller runs, it performs
   the requested action which usually brings in the needed models and renders
   an appropriate view. An action, at its simplest form, is just a controller class
   method whose name starts with action.


class SiteController extends CController
{

   public function actionIndex()

   {

   
    $this->render('index');

   }
}
Yii basics - Model

    • A model represents a single data object. It could be a row in a database table
      or a form of user inputs. Each field of the data object is represented as an
      attribute of the model. The attribute has a label and can be validated against
      a set of rules.

class users extends CActiveRecord {

   /**

     * Returns the static model of the specified AR class.

     * @return CActiveRecord the static model class

     */

   public static function model($className=__CLASS__) {

   
    return parent::model($className);

   }


     /**

       * @return string the associated database table name

       */

     public function tableName() {

     
    return 'users';

     }
Yii basics - View

 • A view is a PHP script consisting of mainly elements of user interface. It can
   contain PHP statements, but it is recommended that these statements should
   not alter data models and should remain relatively simple. For the spirit of
   separation of logic and presentation, large chunk of logic should be placed in
   controller or model instead of view.

<h2>users List</h2>

<div class="actionBar">
[<?php echo CHtml::link('New users',array('create')); ?>]
[<?php echo CHtml::link('Manage users',array('admin')); ?>]
</div>

<?php $this->widget('CLinkPager',array('pages'=>$pages)); ?>
Yii basics - Component

• Yii applications are built upon components which are objects written to a
  specification. A component is an instance of CComponent or its derived
  class. Using a component mainly involves accessing its properties and
  raising/handling its events. The base class CComponent specifies how to
  define properties and events.
Yii basics - Module

• A module is a self-contained software unit that consists of models, views,
  controllers and other supporting components. In many aspects, a module
  resembles to an application. The main difference is that a module cannot be
  deployed alone and it must reside inside of an application. Users can access
  the controllers in a module like they do with normal application controllers.
Creating a application

 • Use the CLI to create the base web application

$ php -f yii/framework/yiic webapp yiidemo
Create a Web application under '/Sites/yiidemo'? [Yes|No] Yes
....
Your application has been created successfully under /Sites/yiidemo.


 • You now have an application with a Home, Contact and Login page
Application - Working with a database

 • To use Yii’s database feature we need to enable PHP PDO extension and the
   driver-specific PDO extension.


 • Edit protected/config/main.php

return array(
   .....
   ‘components’=>array(
       .....
       ‘db’=>array(
           ‘connectionString’=>‘mysql:host=localhost;dbname=yiidemo’,
           ‘username’=>‘yiidemo’,
           ‘password’=>‘yiidemo’,
       ),
   ),
);
Application - Displaying Data

 • To use Yii’s database feature we need to enable PHP PDO extension and the
   driver-specific PDO extension.


 • Edit protected/config/main.php
return array(
   .....
   ‘components’=>array(
       .....
       ‘db’=>array(
           ‘connectionString’=>‘sqlite:protected/data/source.db’,
       ),
   ),
);
Application - Displaying Data

$ php -f yii/framework/yiic shell yiidemo/index.php

Yii Interactive Tool v1.0
Please type 'help' for help. Type 'exit' to quit.
>> model users
   The 'users' class has been successfully created

>> model addresses
 The 'addresses' class has been successfully created

>> crud users
 Crud 'users' has been successfully created.

>> crud addresses
 Crud 'addresses' has been successfully created.
Caching - Data caching

 • Data caching is about storing some PHP variable in the cache and retreiveing
   it later from the cache. For the purpose, the cache component base class
   CCache provides two methods that are used most of the time: set() and get().

Yii::app()->cache->set($id, $value, 30);

$value = Yii:app()->cache->get($id);
if ($value === false)
{
   .....
}


 • delete() and flush() are also available.
Caching - Cache dependency

 • Cached data may also be invalidated according to some dependency
   changes. For example, if we are caching the content of some file and the file
   is changed, we should invalidate the cached copy and read in the latest
   content. We represent a dependency as an instance of CCacheDependency
   or it’s child class. We pass the dependency along while calling set().

$dependency = new CFileCacheDependency(‘FileName.txt’);
Yii::app()->cache->set($id, $value, 30, $dependency);


 • If we retrieve the $value from cache by calling get(), the dependency will be
   evaluated, if changed we will get a boolean false.

 • CFileCacheDependency                     • CGlobalStateCacheDependency

 • CDirectoryCacheDependency                • CChainedStateCacheDependency

 • CDbCacheDependency
Caching - Fragment caching

 • Fragment caching refers to caching a fragment of a page. For example, if a
   page displays a summary of yearly sales figures in a table, we can store this
   table in cache to eliminate the time needed to generate it for each request.


 • To use fragment caching we call beginCache() and endCache() in the
   controller’s view script.

.....HTML CODE.....
<?php if ($this->beginCache($id, array(‘duration’=>36000)) { ?>
.....content to cache.....
<?php $this->endCache($id); } ?>
.....Other HTML content.....

 • You can inject dependencies into fragment caching as well.
Caching - Page caching

 • Page caching refers to the caching of the content of a whole page. Page
   caching can occur at different places. For example, by choosing an
   appropriate page header, the client browser may cache the page being
   viewed for a limited time. The web application itself can also store the page
   content in cache.
public function filters() {
  return array(
     array(
        ‘system.web.widgets.COutputCache’,
        ‘duration’=>100,
        ‘varyByParams’=>array(‘id’),
     ),
  );
}

 • The above configuration would make the filter be applied to all actions in the
   controller. We may limit it to one or a few actions by only using the plus
   operator.
Special - URL Management

 • Creating URLs
$route = ‘post/read’;
$params = array(‘id’=>100);
$url = $this->createUrl($route, $params);
Special - Authentication and Authorization

• In order to authenticate a user, we need to define an identity class which
  contains the actual authentication logic. The identity class should implement
  the IUserIdentity interface.


• The main work in defining an identity class is in the implementation of the
  authenticate method. An identity class may also declare additional identity
  information that needs to be persistent during the user session.
Special - Authentication and Authorization


<?php
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;

     }
}
Special - Authentication and Authorization

 • Login and Logout

// Login a user with the provided username and password.
$identity=new UserIdentity($username,$password);

if($identity->authenticate()) {

      Yii::app()->user->login($identity);
} else {

      echo $identity->errorMessage;
}
......
// Logout the current user
Yii::app()->user->logout();
Special - Theming

• Theming is a systematic way of customizing the outlook of pages in a web
  application. By applying a new theme, the overall appearance of a application
  can be changed instantly and dramatically.


• In Yii each theme is represented as a directory consisting of view files, layout
  files and relevant resources files such as CSS and javascript files. The name
  of a theme is it’s directory name. All themes reside under WebRoot/themes.
Special - Logging

 • Yii provides a flexible and extensible logging feature. Messages logged can
   be classified according to log levels and message categories. Using level and
   category filters, selected messages can be further routed to different
   destinations, such as files, emails, browser windows, etc.

Yii::log($message, $level, $category);
Yii::trace($message, $category);

 • When logging a message it’s $category is a string in the format of xxx.yyy.zzz
   which resembles the path alias. For example if the message is in CController,
   we may use ‘system.web.CCrontoller’.


 • Message level should be one of the following values: trace, info, profile,
   warning, error.
Special - Error Handling

 • Yii defines two exception classes: CException and CHttpException. The
   former is a generic class, while the latter represents an exception that should
   be displayed to end users. The latter also carries a statusCode property
   representing an HTTP status code.
throw new CHttpException(404,'The specified post cannot be found.');
 • When an error is forwarded to the CErrorHandler component, it chooses an
   appropriate view to display the error. If the error is meant to be displayed to
   end users, such as a CHttpException, it will use a view named errorXXX,
   where XXX stands for the statusCode. If it is an internal error not meant to be
   displayed it will use a view named exception.
Special - Web Service

 • A service provider is a class defining the methods that can be remotely
   invoked. Yii relies on doc comment and class reflection to identify which
   methods can be remotely invoked and their parameters and return value.
class StockController extends CController
{
        public function actions()
        {
          return array(‘quote’=>array(‘class’=>‘CWebServiceAction’));
        }
     /**
      * @param string the symbol of the stock
      * @return float the stock price
      * @soap
      */
        public function getPrice($symbol)
        {
          $prices = array(‘IBM’=>100, ‘YHOO’=>28.17);
          return isset($prices[$symbol]) ? $prices[$symbol] : 0;
        }
}
Special - Security

  • Cross-site scripting prevention
<?php $this->beginWidget('CHtmlPurifier'); ?>
...display user-entered content here...
<?php $this->endWidget(); ?>

  • Cross-site request forgery prevention
return array(
   'components'=>array(
      'request'=>array(
         'enableCsrfValidation'=>true,
      ),
   ),
);
  • Cookie attack prevention
return array(
  'components'=>array(
     'request'=>array(
         'enableCookieValidation'=>true,
     ),),);
Special - Performance Tuning

• Enable APC extension


   • This is the easiest way to improve the overall performance of your
     application.


• Disable debug mode


• Use yiilite.php + APC


• Use caching techniques


• Database optimization

Mais conteúdo relacionado

Mais procurados

PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterKHALID C
 
Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireJeff Fox
 
Introduction To CodeIgniter
Introduction To CodeIgniterIntroduction To CodeIgniter
Introduction To CodeIgniterschwebbie
 
Code igniter - A brief introduction
Code igniter - A brief introductionCode igniter - A brief introduction
Code igniter - A brief introductionCommit University
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Benefits of the CodeIgniter Framework
Benefits of the CodeIgniter FrameworkBenefits of the CodeIgniter Framework
Benefits of the CodeIgniter FrameworkToby Beresford
 
Building Web Application Using Spring Framework
Building Web Application Using Spring FrameworkBuilding Web Application Using Spring Framework
Building Web Application Using Spring FrameworkEdureka!
 
Introduction to Ibatis by Rohit
Introduction to Ibatis by RohitIntroduction to Ibatis by Rohit
Introduction to Ibatis by RohitRohit Prabhakar
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring FrameworkEdureka!
 
Progressive EPiServer Development
Progressive EPiServer DevelopmentProgressive EPiServer Development
Progressive EPiServer Developmentjoelabrahamsson
 
Best Practices for JSF, Gameduell 2013
Best Practices for JSF, Gameduell 2013Best Practices for JSF, Gameduell 2013
Best Practices for JSF, Gameduell 2013Edward Burns
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework Rohit Kelapure
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCHitesh-Java
 

Mais procurados (20)

PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniter
 
Introduction To CodeIgniter
Introduction To CodeIgniterIntroduction To CodeIgniter
Introduction To CodeIgniter
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter Bonfire
 
Introduction To CodeIgniter
Introduction To CodeIgniterIntroduction To CodeIgniter
Introduction To CodeIgniter
 
CodeIgniter 101 Tutorial
CodeIgniter 101 TutorialCodeIgniter 101 Tutorial
CodeIgniter 101 Tutorial
 
Code igniter - A brief introduction
Code igniter - A brief introductionCode igniter - A brief introduction
Code igniter - A brief introduction
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Benefits of the CodeIgniter Framework
Benefits of the CodeIgniter FrameworkBenefits of the CodeIgniter Framework
Benefits of the CodeIgniter Framework
 
Spring Mvc
Spring MvcSpring Mvc
Spring Mvc
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Building Web Application Using Spring Framework
Building Web Application Using Spring FrameworkBuilding Web Application Using Spring Framework
Building Web Application Using Spring Framework
 
Introduction to Ibatis by Rohit
Introduction to Ibatis by RohitIntroduction to Ibatis by Rohit
Introduction to Ibatis by Rohit
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring Framework
 
Progressive EPiServer Development
Progressive EPiServer DevelopmentProgressive EPiServer Development
Progressive EPiServer Development
 
Best Practices for JSF, Gameduell 2013
Best Practices for JSF, Gameduell 2013Best Practices for JSF, Gameduell 2013
Best Practices for JSF, Gameduell 2013
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
JSF 2.2
JSF 2.2JSF 2.2
JSF 2.2
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
 

Semelhante a Yii Introduction

Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii FrameworkNoveo
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...LEDC 2016
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindValentine Matsveiko
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigWake Liu
 
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
Spout - Building a RESTful web app with Angular.js and BEAR.SundaySpout - Building a RESTful web app with Angular.js and BEAR.Sunday
Spout - Building a RESTful web app with Angular.js and BEAR.SundayRichard McIntyre
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvCodelyTV
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Dan Wahlin
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For ManagersAgileThought
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 

Semelhante a Yii Introduction (20)

Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii Framework
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Codegnitorppt
CodegnitorpptCodegnitorppt
Codegnitorppt
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
WCLA12 JavaScript
WCLA12 JavaScriptWCLA12 JavaScript
WCLA12 JavaScript
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
The Rails Way
The Rails WayThe Rails Way
The Rails Way
 
Code Igniter 2
Code Igniter 2Code Igniter 2
Code Igniter 2
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
 
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
Spout - Building a RESTful web app with Angular.js and BEAR.SundaySpout - Building a RESTful web app with Angular.js and BEAR.Sunday
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytv
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 

Mais de Jason Ragsdale

Tulsa techfest2010 security
Tulsa techfest2010   securityTulsa techfest2010   security
Tulsa techfest2010 securityJason Ragsdale
 
Tulsa tech fest 2010 - web speed and scalability
Tulsa tech fest 2010  - web speed and scalabilityTulsa tech fest 2010  - web speed and scalability
Tulsa tech fest 2010 - web speed and scalabilityJason Ragsdale
 
Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010Jason Ragsdale
 
Test Driven Development - Tulsa TechFest 2009
Test Driven Development - Tulsa TechFest 2009Test Driven Development - Tulsa TechFest 2009
Test Driven Development - Tulsa TechFest 2009Jason Ragsdale
 
Test Driven Development - 09/2009
Test Driven Development - 09/2009Test Driven Development - 09/2009
Test Driven Development - 09/2009Jason Ragsdale
 
Web Speed And Scalability
Web Speed And ScalabilityWeb Speed And Scalability
Web Speed And ScalabilityJason Ragsdale
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentJason Ragsdale
 

Mais de Jason Ragsdale (8)

Tulsa techfest2010 security
Tulsa techfest2010   securityTulsa techfest2010   security
Tulsa techfest2010 security
 
Tulsa tech fest 2010 - web speed and scalability
Tulsa tech fest 2010  - web speed and scalabilityTulsa tech fest 2010  - web speed and scalability
Tulsa tech fest 2010 - web speed and scalability
 
Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010
 
Test Driven Development - Tulsa TechFest 2009
Test Driven Development - Tulsa TechFest 2009Test Driven Development - Tulsa TechFest 2009
Test Driven Development - Tulsa TechFest 2009
 
Test Driven Development - 09/2009
Test Driven Development - 09/2009Test Driven Development - 09/2009
Test Driven Development - 09/2009
 
What Is Security
What Is SecurityWhat Is Security
What Is Security
 
Web Speed And Scalability
Web Speed And ScalabilityWeb Speed And Scalability
Web Speed And Scalability
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 

Último

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Último (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Yii Introduction

  • 1. Introduction to Jason Ragsdale March 10th, 2009 Dallas PHP MySQL Users Group
  • 2. Framework Features • MVC design pattern • Theming • DAO and Active Record • Web services • jQuery-based JavaScript support • Console applications • I18N and L10N • Authentication and authorization • Page, fragment and data caching • Web 2.0 widgets • Error handling and logging • Form input and validation
  • 3. Yii basics - MVC Overview Static structure of Yii application A typical workflow of Yii application
  • 4. Yii basics - Entry Script • Entry script is the bootstrap PHP script that handles user requests initially. It is the only PHP script that end users can directly request to execute. // remove the following line when in production mode defined('YII_DEBUG') or define('YII_DEBUG',true); // include Yii bootstrap file require_once('path/to/yii/framework/yii.php'); // create application instance and run $configFile='path/to/config/file.php'; Yii::createWebApplication($configFile)->run();
  • 5. Yii basics - Application • Application represents the execution context of request processing. Its main task is to resolve the user request and dispatch it to an appropriate controller for further processing. It also serves as the central place for keeping application-level configurations. For this reason, application is also called front-controller. • Application Configuration array( 'name'=>'Yii Framework', 'defaultController'=>'site', )
  • 6. Yii basics - Controller • A controller is an instance of CController or its child class. It is created by application when the user requests for it. When a controller runs, it performs the requested action which usually brings in the needed models and renders an appropriate view. An action, at its simplest form, is just a controller class method whose name starts with action. class SiteController extends CController { public function actionIndex() { $this->render('index'); } }
  • 7. Yii basics - Model • A model represents a single data object. It could be a row in a database table or a form of user inputs. Each field of the data object is represented as an attribute of the model. The attribute has a label and can be validated against a set of rules. class users extends CActiveRecord { /** * Returns the static model of the specified AR class. * @return CActiveRecord the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'users'; }
  • 8. Yii basics - View • A view is a PHP script consisting of mainly elements of user interface. It can contain PHP statements, but it is recommended that these statements should not alter data models and should remain relatively simple. For the spirit of separation of logic and presentation, large chunk of logic should be placed in controller or model instead of view. <h2>users List</h2> <div class="actionBar"> [<?php echo CHtml::link('New users',array('create')); ?>] [<?php echo CHtml::link('Manage users',array('admin')); ?>] </div> <?php $this->widget('CLinkPager',array('pages'=>$pages)); ?>
  • 9. Yii basics - Component • Yii applications are built upon components which are objects written to a specification. A component is an instance of CComponent or its derived class. Using a component mainly involves accessing its properties and raising/handling its events. The base class CComponent specifies how to define properties and events.
  • 10. Yii basics - Module • A module is a self-contained software unit that consists of models, views, controllers and other supporting components. In many aspects, a module resembles to an application. The main difference is that a module cannot be deployed alone and it must reside inside of an application. Users can access the controllers in a module like they do with normal application controllers.
  • 11. Creating a application • Use the CLI to create the base web application $ php -f yii/framework/yiic webapp yiidemo Create a Web application under '/Sites/yiidemo'? [Yes|No] Yes .... Your application has been created successfully under /Sites/yiidemo. • You now have an application with a Home, Contact and Login page
  • 12. Application - Working with a database • To use Yii’s database feature we need to enable PHP PDO extension and the driver-specific PDO extension. • Edit protected/config/main.php return array( ..... ‘components’=>array( ..... ‘db’=>array( ‘connectionString’=>‘mysql:host=localhost;dbname=yiidemo’, ‘username’=>‘yiidemo’, ‘password’=>‘yiidemo’, ), ), );
  • 13. Application - Displaying Data • To use Yii’s database feature we need to enable PHP PDO extension and the driver-specific PDO extension. • Edit protected/config/main.php return array( ..... ‘components’=>array( ..... ‘db’=>array( ‘connectionString’=>‘sqlite:protected/data/source.db’, ), ), );
  • 14. Application - Displaying Data $ php -f yii/framework/yiic shell yiidemo/index.php Yii Interactive Tool v1.0 Please type 'help' for help. Type 'exit' to quit. >> model users The 'users' class has been successfully created >> model addresses The 'addresses' class has been successfully created >> crud users Crud 'users' has been successfully created. >> crud addresses Crud 'addresses' has been successfully created.
  • 15. Caching - Data caching • Data caching is about storing some PHP variable in the cache and retreiveing it later from the cache. For the purpose, the cache component base class CCache provides two methods that are used most of the time: set() and get(). Yii::app()->cache->set($id, $value, 30); $value = Yii:app()->cache->get($id); if ($value === false) { ..... } • delete() and flush() are also available.
  • 16. Caching - Cache dependency • Cached data may also be invalidated according to some dependency changes. For example, if we are caching the content of some file and the file is changed, we should invalidate the cached copy and read in the latest content. We represent a dependency as an instance of CCacheDependency or it’s child class. We pass the dependency along while calling set(). $dependency = new CFileCacheDependency(‘FileName.txt’); Yii::app()->cache->set($id, $value, 30, $dependency); • If we retrieve the $value from cache by calling get(), the dependency will be evaluated, if changed we will get a boolean false. • CFileCacheDependency • CGlobalStateCacheDependency • CDirectoryCacheDependency • CChainedStateCacheDependency • CDbCacheDependency
  • 17. Caching - Fragment caching • Fragment caching refers to caching a fragment of a page. For example, if a page displays a summary of yearly sales figures in a table, we can store this table in cache to eliminate the time needed to generate it for each request. • To use fragment caching we call beginCache() and endCache() in the controller’s view script. .....HTML CODE..... <?php if ($this->beginCache($id, array(‘duration’=>36000)) { ?> .....content to cache..... <?php $this->endCache($id); } ?> .....Other HTML content..... • You can inject dependencies into fragment caching as well.
  • 18. Caching - Page caching • Page caching refers to the caching of the content of a whole page. Page caching can occur at different places. For example, by choosing an appropriate page header, the client browser may cache the page being viewed for a limited time. The web application itself can also store the page content in cache. public function filters() { return array( array( ‘system.web.widgets.COutputCache’, ‘duration’=>100, ‘varyByParams’=>array(‘id’), ), ); } • The above configuration would make the filter be applied to all actions in the controller. We may limit it to one or a few actions by only using the plus operator.
  • 19. Special - URL Management • Creating URLs $route = ‘post/read’; $params = array(‘id’=>100); $url = $this->createUrl($route, $params);
  • 20. Special - Authentication and Authorization • In order to authenticate a user, we need to define an identity class which contains the actual authentication logic. The identity class should implement the IUserIdentity interface. • The main work in defining an identity class is in the implementation of the authenticate method. An identity class may also declare additional identity information that needs to be persistent during the user session.
  • 21. Special - Authentication and Authorization <?php 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; } }
  • 22. Special - Authentication and Authorization • Login and Logout // Login a user with the provided username and password. $identity=new UserIdentity($username,$password); if($identity->authenticate()) { Yii::app()->user->login($identity); } else { echo $identity->errorMessage; } ...... // Logout the current user Yii::app()->user->logout();
  • 23. Special - Theming • Theming is a systematic way of customizing the outlook of pages in a web application. By applying a new theme, the overall appearance of a application can be changed instantly and dramatically. • In Yii each theme is represented as a directory consisting of view files, layout files and relevant resources files such as CSS and javascript files. The name of a theme is it’s directory name. All themes reside under WebRoot/themes.
  • 24. Special - Logging • Yii provides a flexible and extensible logging feature. Messages logged can be classified according to log levels and message categories. Using level and category filters, selected messages can be further routed to different destinations, such as files, emails, browser windows, etc. Yii::log($message, $level, $category); Yii::trace($message, $category); • When logging a message it’s $category is a string in the format of xxx.yyy.zzz which resembles the path alias. For example if the message is in CController, we may use ‘system.web.CCrontoller’. • Message level should be one of the following values: trace, info, profile, warning, error.
  • 25. Special - Error Handling • Yii defines two exception classes: CException and CHttpException. The former is a generic class, while the latter represents an exception that should be displayed to end users. The latter also carries a statusCode property representing an HTTP status code. throw new CHttpException(404,'The specified post cannot be found.'); • When an error is forwarded to the CErrorHandler component, it chooses an appropriate view to display the error. If the error is meant to be displayed to end users, such as a CHttpException, it will use a view named errorXXX, where XXX stands for the statusCode. If it is an internal error not meant to be displayed it will use a view named exception.
  • 26. Special - Web Service • A service provider is a class defining the methods that can be remotely invoked. Yii relies on doc comment and class reflection to identify which methods can be remotely invoked and their parameters and return value. class StockController extends CController { public function actions() { return array(‘quote’=>array(‘class’=>‘CWebServiceAction’)); } /** * @param string the symbol of the stock * @return float the stock price * @soap */ public function getPrice($symbol) { $prices = array(‘IBM’=>100, ‘YHOO’=>28.17); return isset($prices[$symbol]) ? $prices[$symbol] : 0; } }
  • 27. Special - Security • Cross-site scripting prevention <?php $this->beginWidget('CHtmlPurifier'); ?> ...display user-entered content here... <?php $this->endWidget(); ?> • Cross-site request forgery prevention return array( 'components'=>array( 'request'=>array( 'enableCsrfValidation'=>true, ), ), ); • Cookie attack prevention return array( 'components'=>array( 'request'=>array( 'enableCookieValidation'=>true, ),),);
  • 28. Special - Performance Tuning • Enable APC extension • This is the easiest way to improve the overall performance of your application. • Disable debug mode • Use yiilite.php + APC • Use caching techniques • Database optimization

Notas do Editor

  1. 1. A user makes a request with the URL http://www.example.com/index.php?r=post/show&amp;id=1 and the Web server handles the request by executing the bootstrap script index.php. 2. The bootstrap script creates an application instance and runs it. 3. The application obtains the detailed user request information from an application component named request. 4. The application determines the requested controller and action with the help of an application component named urlManager. For this example, the controller is post which refers to the PostController class; and the action is show whose actual meaning is determined by the controller. 5. The application creates an instance of the requested controller to further handle the user request. The controller determines that the action show refers to a method named actionShow in the controller class. It then creates and executes filters (e.g. access control, benchmarking) associated with this action. The action is executed if it is allowed by the filters. 6. The action reads a Post model whose ID is 1 from the database. 7. The action renders a view named show with the Post model. 8. The view reads and displays the attributes of the Post model. 9. The view executes some widgets. 10. The view rendering result is embedded in a layout. 11. The action completes the view rendering and displays the result to the user.