Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Faster Web Development with Yii 2

Faster Web Development with Yii 2

An introduction to the Yii framework, focusing on the core concepts, how it works, and why you might like it. Given at php[tek] 2014. Uses version 2 of the framework, with explanations of what's new.

Larry Ullman

May 24, 2014
Tweet

More Decks by Larry Ullman

Other Decks in Technology

Transcript

  1. FASTER WEB
    DEVELOPMENT WITH YII 2
    LARRY ULLMAN, @LARRYULLMAN

    PHP[TEK] 2014

    YII.LARRYULLMAN.COM
    Good morning and welcome to my presentation on the Yii framework. Specifically focusing on version 2 of the framework, currently in beta and due for a
    proper release this summer.
    !
    In creating this presentation, I asked myself: What is it that I want to say about the Yii framework?
    !
    http://www.yiiframework.com/wiki/490/creating-a-simple-crud-app-with-yii2-revised-12-20-2013/
    https://github.com/yiisoft/yii2-mongodb

    View full-size slide

  2. YII IS NOT
    THE BEST
    PHP FRAMEWORK.
    First, I’m not going to tell you, or try to convince you, that Yii is the best PHP framework. The question as to what is the best framework is a rather stupid
    one. Although if it helps...

    View full-size slide

  3. FAKE BENCHMARKS
    HTTP://SYSTEMSARCHITECT.NET/PERFORMANCE-BENCHMARK-OF-POPULAR-PHP-FRAMEWORKS/
    ...I can show you benchmarks that suggest Yii is pretty fast.
    !
    Not sure if you’ve seen those benchmarks for creating a “Hello, World” site using a framework. Which, of course, is something you’d never use a framework
    for. Plus, I could, for example, make a Yii site that runs quickly and a Code Igniter site that performs poorly, because I don’t know Code Igniter.
    !
    But, no, I’m not here to show you benchmarks, either.

    View full-size slide

  4. FALSE TRUE
    ARGUE THAT YII IS THE BEST FRAMEWORK

    ARGUE THAT YII IS BETTER THAN X
    FRAMEWORK

    CONVINCE YOU TO SWITCH
    FRAMEWORKS
    TELL YOU WHY YOU MIGHT LIKE YII

    TELL YOU WHY I LIKE YII

    GIVE YOU AN OVERVIEW

    SHOW CODE

    HIGHLIGHT YII2
    $MYGOALSTODAY ===
    So what am I here for?
    [[GO THROUGH FALSE]]
    I’m not a framework expert. I haven’t tried them all and I certainly haven’t mastered them all. So what am I doing here?
    [[GO THROUGH TRUE]]
    !
    I think we all know there’s a huge benefit in knowing more than one framework. Perhaps that second framework should be Yii, if it’s not already.
    !
    For me, for those of you wondering, Yii is my first framework, and maybe Zend is my second maybe. I’ve not tried Laravel, but I’ve heard nothing but good
    things about it.

    View full-size slide

  5. WHAT YOU MIGHT LIKE
    PURE OOP

    MODEL-VIEW-CONTROLLER (MVC)

    ACTIVE RECORD (AR) & PHP DATA OBJECTS (PDO)

    FLEXIBLE AND EXTENDIBLE

    GREAT FOR ADVANCED CASES

    SCALES WELL

    JQUERY BUILT-IN
    As for what you might like about Yii, [[WALK THROUGH]]
    !
    Active Record for Object Relational Mapping (ORM)
    Flexibility: swap ORM, db library, template library (e.g., to Twig), etc.
    !
    component-based architecture
    scales well thanks to its caching abilities
    full-stack, ready-to-use
    !
    high performance is always a goal

    View full-size slide

  6. WHAT I LIKE
    PRETTY CURRENT VERSION OF PHP 5

    DOES A LOT OF THE WORK FOR YOU

    ACCESSIBLE, YET POWERFUL

    VERY CONFIGURABLE

    WORKS WELL WITH THIRD-PARTY SOFTWARE

    FEELS RIGHT

    now 5.4
    spend 80% of your time working on what makes the site unique
    great for beginners, but not unlimited for advanced programmers
    use Zend Framework in parts
    Reminds me of Ruby on Rails

    View full-size slide

  7. LOOKING AT YII 2
    How many people here have used Yii? How many have used Yii 1? Anyone used Yii 2?
    Today I’m going to focus on Yii 2. It’s currently in a very stable beta, meaning all the features have been locked down. It’s being cleaned up now, the docs
    are being finalized, and the first production release should be this summer.
    !
    I wouldn’t use Yii 2 in production today, unless I and extra time, but as Yii 2 is the very near future of the framework, there’s no point in giving a
    presentation on Yii 1.

    View full-size slide

  8. PHP 5.4
    NAMESPACES

    ANONYMOUS FUNCTIONS

    STANDARD PHP LIBRARY (SPL)

    DATE AND TIME CLASSES

    TRAITS

    INTERNATIONALIZATION

    SHORT ARRAY SYNTAX & SHORT ECHO TAGS
    Yii 1 required PHP 5.1; Yii 2 will require PHP 5.4. So the first big difference about Yii 2 is that it takes advantage of more recent features of the language.
    [[WALK THROUGH]]
    !
    namespaces BIG CHANGE, previously prefixed all classes with C
    !
    The naming of the namespaces follows the directory structure. For example, `yii\web\Request`
    indicates the corresponding class file is `web/Request.php` under the Yii framework folder.
    You can use any core class without explicitly including that class file, thanks to the Yii
    class loader.
    !
    built-in RESTful API support
    support for NoSQL
    autoloading, PSR-4, supports third-party autoloaders

    View full-size slide

  9. THE FRAMEWORK
    COMPLETE REWRITE

    DIFFERENT STRUCTURE

    COMPOSER

    PSR

    RESTFUL API SUPPORT

    SUPPORT FOR NOSQL DATABASES

    TWITTER BOOTSTRAP 3

    CONSOLE APPS
    Version 2.0 is a complete rewrite of Yii, adopting the latest technologies and protocols. more beautiful, current, and efficient code; more efficient code
    (e.g., breaking CComponent into Object and Component)
    !
    The framework is installed, and applications are created, using Composer. Extensions are installe via Composer, too.
    !
    Support for PSR, which means lovely autoloaders, and easy support for third-party autoloaders.
    !
    built-in RESTful API support
    !
    support for non-sql (including AR)
    !
    Bootstrap 3 support out of the box
    complex components wrapped in Yii widgets
    !
    improved console applications

    View full-size slide

  10. YII 2 ACTIVERECORD
    MYSQL

    POSTGRESQL

    SQLITE

    SQL SERVER

    CUBRID

    !
    !
    ORACLE

    ELASTICSEARCH

    REDIS

    MONGODB

    SPHINX
    Major improvements for working with databases, including Active Record and query builder
    an also interact with database directly using a PDO layer or query builder
    !
    Class::findOne(id)
    Class:findAll()
    Class::find()
    !
    / to return an active customer whose ID is 1: $customer = Customer::findOne([ 'id' => 1, 'status' => Customer::STATUS_ACTIVE, ]);
    // to return customers whose ID is 1, 2 or 3: $customers = Customer::findAll([1, 2, 3]);

    View full-size slide

  11. TODAY’S PRESENTATION
    GETTING STARTED

    CORE COMPONENTS

    BASIC EDITS AND SCAFFOLDING

    ADVANCED CONCEPTS
    Goal is to highlight the framework, and specifically version 2.
    Going to use a mixture of code and framework overview
    Will build up part of an app live
    Won’t be looking at slides for most of the session
    Could embarrass myself
    !
    Ask questions at any time

    View full-size slide

  12. GETTING STARTED
    see “startin from basic app”
    see Yii2 Steps.txt

    View full-size slide

  13. GETTING STARTED
    CREATING A SITE SHELL

    TESTING THE REQUIREMENTS

    TESTING WHAT YOU HAVE

    GETTING FAMILIAR
    Terminal > Composer
    Load page in Safari
    Load requirements page
    Show features of main page
    static about page, working contact page, functional login
    debugging toolbar (will get back to that)
    The Site’s folders
    framework goes into vendor/
    The Bootstrap File
    web/
    How Yii Handles a Page Request

    View full-size slide

  14. CORE COMPONENTS

    View full-size slide

  15. MVC
    MODEL => DATA & BUSINESS RULES

    VIEW => PRESENTATION (HTML)

    CONTROLLER => AGENT
    Yii generates relations
    Views can renderPartial

    View full-size slide

  16. THE APPLICATION FLOW

    View full-size slide

  17. OBJECT AND COMPONENT CLASSES
    GETTERS & SETTERS

    EVENTS

    BEHAVIORS (MIXINS)
    Info: Nearly every core class in the Yii framework extends from [[yii\base\Object]] or its child class. This means whenever you see a getter or setter in a
    core class, you can use it like a property.
    !
    Now broken into yii\base\Object and yii\base\COmponent
    !
    Object defines getters and setters
    Component extends object and supports events and behaviors
    !
    you can extend Object if you don’t need events and behaviors
    !
    A property defined by a getter without a setter is read only; a property defined by a setter without a getter is write only.
    !
    case-insensitive
    !
    concept-properties.md

    View full-size slide

  18. NAMESPACES
    ALL NAMESPACED UNDER `YII`, POINTS TO VENDOR/YIISOFT/YII2

    `APP` IS AN ALIAS TO THE ROOT DIRECTORY (NOT WEB ROOT)

    View full-size slide

  19. DATABASE INTERACTIONS
    ACTIVERECORD

    FIND()

    FINDBYSQL()

    FINDONE()

    FINDALL()

    QUERYBUILDER

    DATA ACCESS OBJECT
    Major improvements for working with databases, including Active Record and query builder
    an also interact with database directly using a PDO layer or query builder
    !
    Class::findOne(id)
    Class:findAll()
    Class::find()

    View full-size slide

  20. SECURITY
    crypt for password hashing
    $key = \yii\helpers\Security::generateRandomKey();
    !
    Also HtmlPurifier, although you may want to use page caching when using HTML Purifier

    View full-size slide

  21. HELPERS
    ARRAY

    CONSOLE

    FILE

    HTML

    HTMLPURIFIER

    !
    !
    JSON

    MARKDOWN

    SECURITY

    STRING

    URL
    see helper overview

    View full-size slide

  22. AUTHENTICATION & AUTHORIZATION
    BASIC AUTH & AUTH CREATED FOR YOU

    EASILY EXTENDABLE

    AUTHORIZATION VIA

    ACCESS CONTROL FILTER

    ROLE BASED ACCESS CONTROL (RBAC)
    somewhat automatic, pretty easy to implement
    !
    extend IdentityInterface, normal as User model
    !
    authKey is for autologin
    !
    accessToken is OAuth
    !
    You can also do auth via OpenID LDAP, Twitter, Facebook
    !
    Access Control Filter or RBAC

    View full-size slide

  23. WIDGETS
    ACTIVEFORM

    LISTVIEW

    DETAILVIEW

    GRIDVIEW
    For presenting data

    View full-size slide

  24. BOOTSTRAP WIDGETS
    ALERT

    BUTTON, BUTTONDROPDOWN, BUTTONGROUP

    CAROUSEL

    COLLAPSE

    DROPDOWN

    MODAL

    NAV

    PROGRESS

    Used to help with HTML generation
    !
    Bootstrap 3 widgets built-in
    !
    all under \yii\bootstrap
    !

    View full-size slide

  25. BASIC EDITS AND SCAFFOLDING

    View full-size slide

  26. BASIC EDITS AND
    SCAFFOLDING
    INITIAL CONFIGURATION

    GENERATING MODELS

    GENERATING CRUD

    TESTING WHAT YOU HAVE NOW

    DEBUGGING TOOLBAR
    Initial Configuration
    Connecting to the Database
    Managing URLs
    Logging
    Enabling Gii
    !
    Generating Models
    Generating CRUD
    Testing What You Now Have

    View full-size slide

  27. ADVANCED CONCEPTS

    View full-size slide

  28. RESTFUL SERVICE API
    CRAZY EASY

    JSON OR XML OUTPUT

    GET, POST, PUT, DELETE, HEAD

    AUTH & AUTH

    CACHE-ABLE

    CAN BE RATE LIMITED
    see rest-quick-start
    !
    EXAMPLE

    View full-size slide

  29. MODULES
    SELF-CONTAINED MINI-APP

    NESTABLE

    MODULEID/CONTROLLERID/ACTIONID
    Self-contained unit, like a complete Yii application within the application (but cannot be used on its own)
    Examples: admin, forum, store
    Gii can get you started
    New route

    View full-size slide

  30. EXTENSIONS
    APIDOC

    AUTHCLIENT

    BOOTSTRAP

    CODECEPTION

    DEBUG

    ELASTICSEARCH

    GII

    HTMLPURIFIER

    JQUERY USER INTERFACE

    MARKDOWN

    MONGODB

    REDIS

    SMARTY

    SPHINX

    SWIFT MAILER

    TWIG
    More elaborate
    !
    Often third-party
    !
    http://www.yiiframework.com/extensions/
    !
    The ones on this list are official Yii extensions.
    !
    About 30 for Yii 2 right now; 1500+ for Yii 1

    View full-size slide

  31. THIRD-PARTY LIBRARIES
    GREAT SUPPORT FOR THIRD-PARTY LIBRARIES

    CAN EVEN USE OTHER FRAMEWORKS WITHIN YII

    VERY EASY WITH COMPOSER AND PSR

    NOT THAT HARD WITHOUT COMPOSER AND PSR

    View full-size slide

  32. CACHING
    APC

    DB (SQLITE3 BY DEFAULT)

    FILE

    MEMCACHE

    REDIS

    XCACHE

    ZEND DATA
    Can store single piece of data, pages or page fragments, or database stuff
    !
    configure and access a cache component
    !
    Yii::$app->cache
    !
    very easy to switch from one to the other as they all extend from the same base
    set() and get() methods to store and retrieve
    Yii::$app->cache->set($key, $value);
    can set expiration time
    cache dependencies
    !
    use APC for 5.4 or less; Opcache for 5.5 and above
    -enable the opcache
    -cache the AR db schema

    View full-size slide

  33. WHAT ELSE?
    INTERNATIONALIZATION

    TESTING

    CONSOLE APPLICATIONS

    TEMPLATE LIBRARIES

    DEPENDENCY INJECTION CONTAINER

    DATABASE MIGRATIONS
    l18n: message translation, date, time, & number formatting via PHP intl
    !
    testing with codeception
    !
    smarty and twig support built-in
    !
    console applications now automatically generate help output based upon comment blocks!
    !
    Dependency Injection container (http://martinfowler.com/articles/injection.html)
    !
    database migrations

    View full-size slide

  34. FASTER WEB
    DEVELOPMENT WITH YII 2
    LARRY ULLMAN, @LARRYULLMAN

    PHP[TEK] 2014

    YII.LARRYULLMAN.COM

    View full-size slide