GET THINGS DONE WITH QUICKLY BUILD A WEBAPP USING YII  GIULIANO IACOBELLI - @Giuliano84 - me@giulianoiacobelli.com
WEB IS FULL OF AMAZING TOOLS
USUALLY EVERYTHING STARTS      FROM AN IDEA
IF IT’S THE RIGHT ONEAND IS WELL EXECUTED..
IF YOU HAVE GOOD IDEA, DO IT.MOVE FAST ANDBREAK THINGS
SO LET ME INTRODUCE YOU TO
WHAT IS IT?Yii is a high-performance component-basedPHP framework for developing large-scaleWebapplications. It enables ma...
IT’S EASY?IT’S RAPID?IT’S SECURE?         YES IT IS (YII) !!!
THE MVC PATTERNMVC is a design patternwidely adopted in Webprogramming that aims toseparate business logic fromuser interf...
THE MVC PATTERN Assume a Web application consists of several sub- applications:• Front end: a public-facing website for no...
M for MODEL Models are used to keep data and their relevant business rules. A model represents a single data object that c...
C for CONTROLLERControllers are the glue that binds models, views and othercomponents together into a runnable application...
V for VIEWA view is a PHP script consisting of mainly elements of user interfacethe spirit of seperation of logic and pres...
STRUCTURE OF YII APPLICATION
THE ENTRY SCRIPTThis is a “bootstrap” file, meaning that all user interactions actuallygo through it. For example, showing...
YII WORKFLOW      1 - Request with the URL      http://example.com/index.php?r=post/      show&id=1 and the Web server han...
YII WORKFLOW      5 - The application creates an instance of the      requested controller to further handle the      user...
OK, OK, I GOT IT, TOO MUCH TALK..LET’S HAVE AN IDEA TO BUILD..
AND THE AMAZING IDEA IS..
A BLOG!OK, IT’S NOT THAT AMAZING BUT IN THISWAY I’M PRETTY SURE THAT ALL OF YOU KNOW WHAT WE ARE GOIN TO BUILD
WARM UP • CREATE A “BLOGDEMO” FOLDER   IN YOUR APACHE DOCUMENT   ROOT DIRECTORY • DOWNLOAD YiiBlogDemo.zip FILE   FROM htt...
YII PREPARATIONRun a simple console command“blogdemo/framework/yiic         webapp ../“to generate a skeleton Web applicat...
THE WEB APPLICATIONThe application is fully functional, with nice featuresincluding user login and contact form. It is a g...
WHAT A BLOG USUALLY HAVE?              •   POSTS              •   USERS              •   COMMENTS              •   TAGS
DBSCHEMA.SQL
SETTING UP THE DATABASEreturn array(     ......     components=>array(          ......         db=>array(              con...
GENERATING THE MODELSWe need to create a model class for each of our databasetables. Yii has an amazing component called G...
GII MODEL GENERATOR
OUR MODELS• User.php contains the User class and can be used to access  the tbl_user database table;• Post.php contains th...
CRUD OPERATIONSAfter the model classes are created, we can use the CrudGenerator to generate the code implementing the CRU...
AUTHENTICATING USEROur blog application needs to differentiate betweenthe system owner and guest users. Therefore, we need...
AUTHENTICATING USERApplication already provides user authenticationby checking if the username and password areboth demo o...
EDITING USERIDENTITY.PHPpublic function authenticate(){    $username=strtolower($this->username);    $user=User::model()->...
RECAP• Identified the requirements to be fulfilled;• We installed the Yii framework and created a skeleton  application;• ...
CUSTOMIZING POST MODELPost model generated is fine but now we need to specifyvalidation rules and related objects• Validat...
VALIDATION RULESBased on the requirement analysis, we modify therules() method as follows:public function rules(){    retu...
MODEL RELATIONSWe customize relations() method as followpublic function relations(){    return array(        author => arr...
REPRESENTING STATUS IN TEXTBecause the status of a post is stored as an integer in thedatabase, we need to provide a textu...
LOOKUP.PHPclass Lookup extends CActiveRecord{    private static $_items=array();    public static function items($type)   ...
POST POSSIBLE STATUSES              class Post extends CActiveRecord              {                  const STATUS_DRAFT=1;...
CONFIGURING ACCESS RULESpublic function accessRules(){    return array(        array(allow, // allow all users to perform ...
CREATE AND UPDATEThe create and update operations are very similar. They bothneed to display an HTML form to collect user ...
CREATE AND UPDATEWe then modify the Post class so that it can automatically setsome attributes (create_time, author_id) be...
STYLE MATTERS
HOW TO BORROW SOME STYLE?  http://twitter.github.com/bootstrap
QUICKLY BUILD A NICE UI
WEB AS CONCEPT IS REALLY WIDE
MOBILEFIRST!
LOOK AT THE NUMBERS http://www.phonecount.com/pc/count.jsp
RESPONSIVE DESIGN 101
BOOTSTRAP RESPONSIVENESSIt supports a handful of media queries in a single file tohelp make your projects appropriate on d...
Thanks                                    Giuliano Iacobelli                                         giuliano.iacobelli   ...
Get things done with Yii - quickly build webapplications
Upcoming SlideShare
Loading in...5
×

Get things done with Yii - quickly build webapplications

34,853

Published on

Lesson teached at Università di Roma Tre - Software Engineering course.

Web is plenty of amazing tools used daily by millions of people. A good idea can turn to be a highly profitable business if well executed. Yii framework is an ideal tool to build in short time an MVP of your product to start as soon as possible to find your market fit. Here follows some infos about the framework and steps on how to build a simple blog over Yii.

Published in: Technology
1 Comment
42 Likes
Statistics
Notes
No Downloads
Views
Total Views
34,853
On Slideshare
0
From Embeds
0
Number of Embeds
26
Actions
Shares
0
Downloads
737
Comments
1
Likes
42
Embeds 0
No embeds

No notes for slide

Get things done with Yii - quickly build webapplications

  1. 1. GET THINGS DONE WITH QUICKLY BUILD A WEBAPP USING YII GIULIANO IACOBELLI - @Giuliano84 - me@giulianoiacobelli.com
  2. 2. WEB IS FULL OF AMAZING TOOLS
  3. 3. USUALLY EVERYTHING STARTS FROM AN IDEA
  4. 4. IF IT’S THE RIGHT ONEAND IS WELL EXECUTED..
  5. 5. IF YOU HAVE GOOD IDEA, DO IT.MOVE FAST ANDBREAK THINGS
  6. 6. SO LET ME INTRODUCE YOU TO
  7. 7. WHAT IS IT?Yii is a high-performance component-basedPHP framework for developing large-scaleWebapplications. It enables maximumreusability in Web programming and cansignificantly accelerate the developmentprocess.
  8. 8. IT’S EASY?IT’S RAPID?IT’S SECURE? YES IT IS (YII) !!!
  9. 9. THE MVC PATTERNMVC is a design patternwidely adopted in Webprogramming that aims toseparate business logic fromuser interfaceconsiderations, so thatdevelopers can more easilychange each part withoutaffecting the other.
  10. 10. THE MVC PATTERN Assume a Web application consists of several sub- applications:• Front end: a public-facing website for normal end users;• Back end: a website that exposes administrative functionality for managing the application.• Console: an application consisting of console commands to be run in a terminal window or as scheduled jobs to support the whole application;• Web API: providing interfaces to third parties for integrating with the application.
  11. 11. M for MODEL Models are used to keep data and their relevant business rules. A model represents a single data object that could be a row in a database table or a form of user inputs.• should contain properties to represent specific data;• should contain business logic (e.g. validation rules) to ensure the represented data fulfills the design requirement;• may contain code for manipulating data. For example, a SearchForm model, besides representing the search input data, may contain a search method to implement the actual search.
  12. 12. C for CONTROLLERControllers are the glue that binds models, views and othercomponents together into a runnable application. They areresponsible for dealing directly with end user requests.• may access $_GET, $_POST and other PHP variables that represent user requests;• may create model instances and manage their life cycles.• should avoid containing embedded SQL statements, which are better kept in models.• should avoid containing any HTML or any other presentational markup. This is better kept in views.
  13. 13. V for VIEWA view is a PHP script consisting of mainly elements of user interfacethe spirit of seperation of logic and presentation, large chunk of logicshould be placed in controller or model instead of view.• should mainly contain presentational code, such as HTML, and simple PHP code to traverse, format and render data;• should avoid containing code that performs explicit DB queries. Such code is better placed in models.• should avoid direct access to $_GET, $_POST, or other similar variables that represent the end user request. This is the controllers job.
  14. 14. STRUCTURE OF YII APPLICATION
  15. 15. THE ENTRY SCRIPTThis is a “bootstrap” file, meaning that all user interactions actuallygo through it. For example, showing an employee record might bethrough the URL. It is the only PHP script that end users can directlyrequest 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();
  16. 16. YII WORKFLOW 1 - Request with the URL http://example.com/index.php?r=post/ show&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 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.
  17. 17. YII WORKFLOW 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. 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,10,11 - The view executes some widgets, embed the rendering result in a layout and displays it to the user.
  18. 18. OK, OK, I GOT IT, TOO MUCH TALK..LET’S HAVE AN IDEA TO BUILD..
  19. 19. AND THE AMAZING IDEA IS..
  20. 20. A BLOG!OK, IT’S NOT THAT AMAZING BUT IN THISWAY I’M PRETTY SURE THAT ALL OF YOU KNOW WHAT WE ARE GOIN TO BUILD
  21. 21. WARM UP • CREATE A “BLOGDEMO” FOLDER IN YOUR APACHE DOCUMENT ROOT DIRECTORY • DOWNLOAD YiiBlogDemo.zip FILE FROM http://goo.gl/nOqef AND UNZIP IT • OPEN FRAMEWORK.ZIP AND PLACE ITS CONTENT IN YOUR “BLOGDEMO” FOLDER
  22. 22. YII PREPARATIONRun a simple console command“blogdemo/framework/yiic webapp ../“to generate a skeleton Web application built with Yii.This will create a skeleton Yii application under thedirectory WebRoot/testdrive.
  23. 23. THE WEB APPLICATIONThe application is fully functional, with nice featuresincluding user login and contact form. It is a good startingpoint for implementing more sophisticated features.
  24. 24. WHAT A BLOG USUALLY HAVE? • POSTS • USERS • COMMENTS • TAGS
  25. 25. DBSCHEMA.SQL
  26. 26. SETTING UP THE DATABASEreturn array( ...... components=>array( ...... db=>array( connectionString => mysql:host=localhost;dbname=blog, emulatePrepare => true, username => root, password => , charset => utf8, tablePrefix => tbl_, ), ), ......);
  27. 27. GENERATING THE MODELSWe need to create a model class for each of our databasetables. Yii has an amazing component called Gii that totallyautomates this process (known as scaffolding) for us. modules=>array( gii=>array( class=>system.gii.GiiModule, password=>pick up a password here, ), ),
  28. 28. GII MODEL GENERATOR
  29. 29. OUR MODELS• User.php contains the User class and can be used to access the tbl_user database table;• Post.php contains the Post class and can be used to access the tbl_post database table;• Tag.php contains the Tag class and can be used to access the tbl_tag database table;• Comment.php contains the Comment class and can be used to access the tbl_comment database table;• Lookup.php contains the Lookup class and can be used to access the tbl_lookup database table.
  30. 30. CRUD OPERATIONSAfter the model classes are created, we can use the CrudGenerator to generate the code implementing the CRUDoperations for these models. We will do this for the Postand Comment models.
  31. 31. AUTHENTICATING USEROur blog application needs to differentiate betweenthe system owner and guest users. Therefore, we needto implement the user authentication featureUser authentication is performed in a classimplementing the IUserIdentity interface. The skeletonapplication uses the UserIdentity class for thispurpose.The class is stored in the file /wwwroot/blogdemo/protected/components/UserIdentity.php.
  32. 32. AUTHENTICATING USERApplication already provides user authenticationby checking if the username and password areboth demo or admin.Now we will modify the corresponding code sothat the authentication is done against the Userdatabase table.
  33. 33. EDITING USERIDENTITY.PHPpublic function authenticate(){ $username=strtolower($this->username); $user=User::model()->find(LOWER(username)=?,array($username)); if($user===null) $this->errorCode=self::ERROR_USERNAME_INVALID; else if(!$user->validatePassword($this->password)) $this->errorCode=self::ERROR_PASSWORD_INVALID; else { $this->_id=$user->id; $this->username=$user->username; $this->errorCode=self::ERROR_NONE; } return $this->errorCode==self::ERROR_NONE;}public function getId(){ return $this->_id;}
  34. 34. RECAP• Identified the requirements to be fulfilled;• We installed the Yii framework and created a skeleton application;• We designed and created the blog database;• We generated basic CRUD operations;• We modified the authentication method to check against the tbl_user table.
  35. 35. CUSTOMIZING POST MODELPost model generated is fine but now we need to specifyvalidation rules and related objects• Validation rules ensure the attribute values entered by users are correct before they are saved to the database. For example, the status attribute of Post should be an integer 1, 2 or 3.• Customizing the relations we can exploit the powerful Relational ActiveRecord (RAR) feature to access the related object information of a post, such as its author and comments, without the need to write complex SQL statements.
  36. 36. VALIDATION RULESBased on the requirement analysis, we modify therules() method as follows:public function rules(){ return array( array(title, content, status, required), array(title, length, max=>128), array(status, in, range=>array(1,2,3)), array(tags, match, pattern=>/^[ws,]+$/, message=>Tags can only contain word characters.), array(tags, normalizeTags), array(title, status, safe, on=>search), );}
  37. 37. MODEL RELATIONSWe customize relations() method as followpublic function relations(){ return array( author => array(self::BELONGS_TO, User, author_id), comments => array(self::HAS_MANY, Comment, post_id, condition=>comments.status=.Comment::STATUS_APPROVED, order=>comments.create_time DESC), commentCount => array(self::STAT, Comment, post_id, condition=>status=.Comment::STATUS_APPROVED), );}We also introduce in the Comment class Comment extends CActiveRecord {model class two constants that are const STATUS_PENDING=1;used in the above method: const STATUS_APPROVED=2; ...... }
  38. 38. REPRESENTING STATUS IN TEXTBecause the status of a post is stored as an integer in thedatabase, we need to provide a textual representation so that itis more intuitive when being displayed to end users. In a largesystem, the similar requirement is very common.As a generic solution, we use the tbl_lookup table to store themapping between integer values and textual representationsthat are needed by other data objects.We modify the Lookup model class as follows to more easilyaccess the textual data in the table.
  39. 39. LOOKUP.PHPclass Lookup extends CActiveRecord{ private static $_items=array(); public static function items($type) { if(!isset(self::$_items[$type])) self::loadItems($type); return self::$_items[$type]; } public static function item($type,$code) { if(!isset(self::$_items[$type])) self::loadItems($type); return isset(self::$_items[$type][$code]) ? self::$_items[$type][$code] : false; } private static function loadItems($type) { self::$_items[$type]=array(); $models=self::model()->findAll(array( condition=>type=:type, params=>array(:type=>$type), order=>position, )); foreach($models as $model) self::$_items[$type][$model->code]=$model->name; }}
  40. 40. POST POSSIBLE STATUSES class Post extends CActiveRecord { const STATUS_DRAFT=1; const STATUS_PUBLISHED=2; const STATUS_ARCHIVED=3; ...... }Now we can call Lookup::items(PostStatus) to get thelist of possible post statuses (text strings indexed by thecorresponding integer values), and callLookup::item(PostStatus, Post::STATUS_PUBLISHED) toget the string representation of the published status.
  41. 41. CONFIGURING ACCESS RULESpublic function accessRules(){ return array( array(allow, // allow all users to perform list and showactions actions=>array(index, view), users=>array(*), ), array(allow, // allow authenticated users to perform any action users=>array(@), ), array(deny, // deny all users users=>array(*), ), );} The rules state that all users can access the index and view actions, and authenticated users can access any actions, including the admin action.
  42. 42. CREATE AND UPDATEThe create and update operations are very similar. They bothneed to display an HTML form to collect user inputs, validatethem, and save them into database.Gii generates a partial view /wwwroot/blog/protected/views/post/_form.php that is embedded in both the create and updateviews to render the needed HTML form.We want to add a dropdown list to collect user input for STATUSattributeecho $form->dropDownList($model,status,Lookup::items(PostStatus));
  43. 43. CREATE AND UPDATEWe then modify the Post class so that it can automatically setsome attributes (create_time, author_id) before a post issaved to the database. We override the beforeSave() methodas follows protected function beforeSave() { if(parent::beforeSave()) { if($this->isNewRecord) { $this->create_time=$this->update_time=time(); $this->author_id=Yii::app()->user->id; } else $this->update_time=time(); return true; } else return false; }
  44. 44. STYLE MATTERS
  45. 45. HOW TO BORROW SOME STYLE? http://twitter.github.com/bootstrap
  46. 46. QUICKLY BUILD A NICE UI
  47. 47. WEB AS CONCEPT IS REALLY WIDE
  48. 48. MOBILEFIRST!
  49. 49. LOOK AT THE NUMBERS http://www.phonecount.com/pc/count.jsp
  50. 50. RESPONSIVE DESIGN 101
  51. 51. BOOTSTRAP RESPONSIVENESSIt supports a handful of media queries in a single file tohelp make your projects appropriate on different devicesand screen resolutions. @media (min-width:400px) { }
  52. 52. Thanks Giuliano Iacobelli giuliano.iacobelli me@giulianoiacobelli.com http://giulianoiacobelli.com Connect with me:Ps: slide 47 and 48 were borrowed from this amazing presentation of Brad Frost
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×