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

An Introduction To Yii Framework 2 - (DPUG 11/11/14)

An Introduction To Yii Framework 2 - (DPUG 11/11/14)

Jason will be introducing you to the latest version of the Yii framework, version 2. According to the Yii site, the framework is "a high-performance PHP framework best for developing Web 2.0 applications. Yii comes with rich features: MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access control, scaffolding, testing, etc. It can reduce your development time significantly."

Jason Ragsdale

November 11, 2014
Tweet

More Decks by Jason Ragsdale

Other Decks in Technology

Transcript

  1. An Introduction To
    Jason Ragsdale - Dallas PHP Users Group - 11/11/2014
    1
    2

    View Slide

  2. 2
    Introduction to Yii2 -
    !
    1 2 3 4
    Introduction Features Setup & Install Database & Models
    5 6 7 8
    Helpers Extensions Q&A
    What is Yii2 What does it provide Get up and running quickly Working with data
    Making things easier Extending functionality
    2
    Fin!

    View Slide

  3. 3
    Introduction
    Introduction to Yii2 - Jason Ragsdale
    !
    • PHP >= 5.4.x
    • MVC (Model-Vew-Controller)
    • Extendable
    • Simple
    • High Performance
    2
    What is Yii2

    View Slide

  4. What does it provide
    4
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC

    View Slide

  5. What does it provide
    5
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Creating a model
    namespace app\models;


    use yii\base\Model;


    class ContactForm extends Model

    {

    public $name;

    public $email;

    public $subject;

    public $body;

    }

    View Slide

  6. What does it provide
    6
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Attribute labels
    public function attributeLabels()

    {

    return [

    'name' => 'Your name',

    'email' => 'Your email address',

    'subject' => 'Subject',

    'body' => 'Content',

    ];

    }

    View Slide

  7. What does it provide
    7
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Labels w/ translations
    public function attributeLabels()

    {

    return [

    'name' => \Yii::t('app', 'Your name'),

    'email' => \Yii::t('app', 'Your email address'),

    'subject' => \Yii::t('app', 'Subject'),

    'body' => \Yii::t('app', 'Content'),

    ];

    }

    View Slide

  8. What does it provide
    8
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Scenarios
    public function scenarios()

    {

    $scenarios = parent::scenarios();

    $scenarios['login'] = ['username', 'password'];

    $scenarios['register'] = ['username', 'email', 'password'];

    return $scenarios;

    }

    View Slide

  9. What does it provide
    9
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Rules
    public function rules()

    {

    return [

    // the name, email, subject and body attributes are required

    [['name', 'email', 'subject', 'body'], 'required'],


    // the email attribute should be a valid email address

    ['email', 'email'],

    ];

    }

    View Slide

  10. What does it provide
    10
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Creating a view
    /* @var $this yii\web\View */

    /* @var $form yii\widgets\ActiveForm */

    /* @var $model app\models\LoginForm */


    $this->title = 'Login';

    ?>

    = Html::encode($this->title) ?>


    Please fill out the following fields to login:



    = $form->field($model, 'username') ?>

    = $form->field($model, 'password')->passwordInput() ?>

    = Html::submitButton('Login') ?>


    View Slide

  11. What does it provide
    11
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Layouts
    beginPage() ?>





    = Html::csrfMetaTags() ?>

    = Html::encode($this->title) ?>

    head() ?>


    beginBody() ?>

    My Company

    = $content ?>

    © 2014 by My Company

    endBody() ?> 

    endPage() ?>

    View Slide

  12. What does it provide
    12
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Creating a controller
    namespace app\controllers;


    use yii\web\Controller;


    class SiteController extends Controller

    {

    }

    View Slide

  13. What does it provide
    13
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Adding actions
    public function actionIndex()

    {

    return $this->render('index');

    }


    public function actionHelloWorld()

    {

    return 'Hello World';

    }

    View Slide

  14. What does it provide
    14
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    MVC
    Actions with params
    public function actionView($id, $version = null)

    {

    $model = $this->findModel($id, $version);


    if ($model) {

    return $this->render('view', ['model' => $model]);

    }


    throw new NotFoundHttpException('Record not found');

    }

    View Slide

  15. { }
    Authentication & Authorization
    What does it provide
    15
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2

    View Slide

  16. What does it provide
    16
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Authentication
    class User extends ActiveRecord implements IdentityInterface
    'user' => [

    'identityClass' => 'common\models\User',

    'enableAutoLogin' => true,

    ],
    public static function findIdentity($id);
    public static function findIdentityByAccessToken($token, $type = null);
    public function getId();
    public function getAuthKey();
    public function validateAuthKey($authKey);
    { }
    Authentication & Authorization

    View Slide

  17. What does it provide
    17
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Authorization
    'access' => [

    'class' => AccessControl::className(),

    'only' => ['login', 'logout', 'signup'],

    'rules' => [

    [

    'allow' => true,

    'actions' => ['login', 'signup'],

    'roles' => ['?'],

    ],

    [

    'allow' => true,

    'actions' => ['logout'],

    'roles' => ['@'],

    ],

    ],

    ],
    { }
    Authentication & Authorization

    View Slide

  18. What does it provide
    18
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Hashing & Verifying Passwords
    // Hashing passwords

    $hash = Yii::$app->getSecurity()->generatePasswordHash($password);


    // Verifying passwords

    if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {

    // all good, logging user in

    } else {

    // wrong password

    }
    { }
    Authentication & Authorization

    View Slide

  19. What does it provide
    19
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Encryption & Decryption
    // $data and $secretKey are obtained from the form

    $encryptedData = Yii::$app->getSecurity()->encryptByPassword($data, $secretKey);

    // store $encryptedData to database


    // $secretKey is obtained from user input, $encryptedData is from the database

    $data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $secretKey);
    { }
    Authentication & Authorization

    View Slide

  20. What does it provide
    20
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    Authentication & Authorization
    Confirming Data Integrity
    // $secretKey our application secret, $genuineData obtained from a reliable source

    $data = Yii::$app->getSecurity()->hashData($genuineData, $secretKey);


    // $secretKey our application secret, $data obtained from an unreliable source

    $data = Yii::$app->getSecurity()->validateData($data, $secretKey);

    View Slide

  21. What does it provide
    21
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    RBAC

    View Slide

  22. What does it provide
    22
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    RBAC
    'components' => [

    'authManager' => [

    'class' => 'yii\rbac\PhpManager',

    // 'class' => 'yii\rbac\DbManager',

    ],

    ],

    View Slide

  23. What does it provide
    23
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    RBAC
    $auth = Yii::$app->authManager;


    // add "createPost" permission

    $createPost = $auth->createPermission('createPost');

    $createPost->description = 'Create a post';

    $auth->add($createPost);


    // add "author" role and give this role the "createPost" permission

    $author = $auth->createRole('author');

    $auth->add($author);

    $auth->addChild($author, $createPost);


    // Assign the author role to user 2

    $auth->assign($author, 2);

    View Slide

  24. { }
    Caching
    What does it provide
    24
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2

    View Slide

  25. What does it provide
    25
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    • APC
    • Db
    • Dummy
    • File
    • Memcache
    • Redis
    • WinCache
    • Xcache
    { }
    Caching

    View Slide

  26. What does it provide
    26
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    • Data caching
    • Fragment caching
    • Page caching
    • HTTP caching
    { }
    Caching

    View Slide

  27. What does it provide
    27
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Data
    'components' => [

    'cache' => [

    'class' => 'yii\caching\ApcCache',

    ],

    ],
    { }
    Caching

    View Slide

  28. What does it provide
    28
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Data
    'cache' => [

    'class' => 'yii\caching\MemCache',

    'servers' => [

    [

    'host' => 'server1',

    'port' => 11211,

    'weight' => 100,

    ],

    [

    'host' => 'server2',

    'port' => 11211,

    'weight' => 50,

    ],

    ],

    ],
    { }
    Caching

    View Slide

  29. What does it provide
    29
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Dependencies
    •Chained
    •Db
    •Expression
    •File
    •Tag
    { }
    Caching

    View Slide

  30. What does it provide
    30
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Query
    'db' => [

    'class' => 'yii\db\Connection',

    'enableSchemaCache' => true,

    'schemaCacheDuration' => 3600,

    'schemaCacheExclude' => [],

    'schemaCache' => 'cache',

    'enableQueryCache' => true,

    'queryCacheDuration' => 3600,

    'queryCache' => 'cache',

    ],
    { }
    Caching

    View Slide

  31. What does it provide
    31
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Fragment
    if ($this->beginCache($id, ['duration' => 3600])) {

    // ... generate content here ...

    $this->endCache();

    }
    { }
    Caching

    View Slide

  32. What does it provide
    32
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Fragment
    $dependency = [

    'class' => 'yii\caching\DbDependency',

    'sql' => 'SELECT MAX(updated_at) FROM post',

    ];


    if ($this->beginCache($id, ['dependency' => $dependency])) {

    // ... generate content here ...

    $this->endCache();

    }
    { }
    Caching

    View Slide

  33. What does it provide
    33
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Fragment
    if ($this->beginCache($id, ['variations' => [Yii::$app->language]])) {

    // ... generate content here ...

    $this->endCache();

    }
    { }
    Caching

    View Slide

  34. What does it provide
    34
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Page
    public function behaviors()

    {

    return [

    [

    'class' => 'yii\filters\PageCache',

    'only' => ['index'],

    'duration' => 60,

    'variations' => [

    \Yii::$app->language,

    ],

    'dependency' => [

    'class' => 'yii\caching\DbDependency',

    'sql' => 'SELECT COUNT(*) FROM post',

    ],

    ],

    ];

    }
    { }
    Caching

    View Slide

  35. What does it provide
    35
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    HTTP
    public function behaviors()

    {

    return [

    [

    'class' => 'yii\filters\HttpCache',

    'only' => [‘index'],

    'lastModified' => function ($action, $params) {

    $q = new \yii\db\Query();

    return $q->from('post')->max('updated_at');

    },

    'etagSeed' => function ($action, $params) {

    $post = $this->findModel(\Yii::$app->request->get('id'));

    return serialize([$post->title, $post->content]);

    },

    ],

    ];

    }
    { }
    Caching

    View Slide

  36. What does it provide
    36
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    RESTful Web Services

    View Slide

  37. { }
    What does it provide
    37
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    • Default JSON & XML response format support
    • Customizable object serialization
    • Proper formatting of collection data and validation errors
    • Support for HATEOAS
    • Efficient routing with proper HTTP verb check
    • Built-in support for the OPTIONS and HEAD verbs
    • Authentication and authorization
    • Data caching and HTTP caching
    • Rate limiting
    RESTful Web Services

    View Slide

  38. What does it provide
    38
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    'request' => [

    'parsers' => [

    'application/json' => 'yii\web\JsonParser',

    ]

    ],

    'urlManager' => [

    'rules' => [

    [

    'class' => 'yii\rest\UrlRule', 

    'controller' => 'user'

    ],

    ],

    ],
    { }
    RESTful Web Services

    View Slide

  39. What does it provide
    39
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    namespace app\controllers;


    use yii\rest\ActiveController;


    class UserController extends ActiveController

    {

    public $modelClass = 'app\models\User';

    }
    { }
    RESTful Web Services
    Controller Setup

    View Slide

  40. What does it provide
    40
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    • GET /users: list all users page by page;
    • HEAD /users: show the overview information of user listing;
    • POST /users: create a new user;
    • GET /users/123: return the details of the user 123;
    • HEAD /users/123: show the overview information of user 123;
    • PATCH /users/123 and PUT /users/123: update the user 123;
    • DELETE /users/123: delete the user 123;
    • OPTIONS /users: show the supported verbs regarding endpoint /users;
    • OPTIONS /users/123: show the supported verbs regarding endpoint /users/
    123.
    { }
    RESTful Web Services
    Methods Exposed

    View Slide

  41. What does it provide
    41
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    RESTful Web Services
    HATEOAS
    class User extends ActiveRecord implements Linkable

    {

    public function getLinks()

    {

    return [

    Link::REL_SELF => Url::to(['user/view', 'id' => $this->id], true),

    ];

    }

    }

    View Slide

  42. What does it provide
    42
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    RESTful Web Services
    HATEOAS
    {
    "id": 100,
    "email": "[email protected]",
    // ...
    "_links" => [
    "self": "https://example.com/users/100"
    ]
    }

    View Slide

  43. What does it provide
    43
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    RESTful Web Services
    Collections & Serializer
    class PostController extends Controller

    {

    public function actionIndex()

    {

    return new ActiveDataProvider([

    'query' => Post::find(),

    ]);

    }

    }
    X-Pagination-Total-Count: The total number of resources
    X-Pagination-Page-Count: The number of pages
    X-Pagination-Current-Page: The current page (1-based)
    X-Pagination-Per-Page: The number of resources in each page;
    Link: A set of navigational links allowing client to traverse the resources page by page.

    View Slide

  44. What does it provide
    44
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    CLI

    View Slide

  45. What does it provide
    45
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    CLI
    namespace app\commands;


    use yii\console\Controller;


    class HelloController extends Controller

    {

    /**

    * This command echoes what you have entered as the message.

    * @param string $message the message to be echoed.

    */

    public function actionIndex($message = 'hello world')

    {

    echo $message . "\n";

    }

    }

    View Slide

  46. What does it provide
    46
    Features
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    { }
    Testing & Gii
    DEMO

    View Slide

  47. 47
    Setup & Install
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Get up and running quickly
    // Used to support npm/bower assets via composer
    $ composer global require "fxp/composer-asset-plugin:1.0.0-beta3"
    // Setup a basic app
    $ composer create-project --prefer-dist yiisoft/yii2-app-basic myapp

    // Setup a advanced app
    $ composer create-project --prefer-dist yiisoft/yii2-app-advanced myapp
    Composer bootstrapping
    http://localhost/myapp/web/

    View Slide

  48. 48
    Setup & Install
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Get up and running quickly
    return [

    'class' => 'yii\db\Connection',

    'dsn' => 'mysql:host=localhost;dbname=myapp',

    //'dsn' => 'sqlite:/path/to/database/file', // SQLite

    //'dsn' => 'pgsql:host=localhost;port=5432;dbname=myapp', // PostgreSQL

    //'dsn' => 'cubrid:dbname=myapp;host=localhost;port=33000', // CUBRID

    //'dsn' => 'sqlsrv:Server=localhost;Database=myapp', // MS SQL Server, sqlsrv

    //'dsn' => 'dblib:host=localhost;dbname=myapp', // MS SQL Server, dblib

    //'dsn' => 'mssql:host=localhost;dbname=myapp', // MS SQL Server, mssql

    //'dsn' => 'oci:dbname=//localhost:1521/myapp', // Oracle

    'username' => 'root',

    'password' => '',

    'charset' => 'utf8',

    ];
    Edit config/db.php

    View Slide

  49. 49
    Database & Models
    Introduction to Yii2 - Jason Ragsdale
    !
    • DAO
    • Query Builder
    • Active Record
    • Migrations
    2
    Dealing with data

    View Slide

  50. 50
    Database & Models
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Dealing with data
    { }
    DAO
    $connection = \Yii::$app->db;


    $command = $connection->createCommand('SELECT * FROM post');

    $posts = $command->queryAll();


    $command = $connection->createCommand('SELECT * FROM post WHERE id=1');

    $post = $command->queryOne();

    View Slide

  51. 51
    Database & Models
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Dealing with data
    { }
    Query Builder
    $rows = (new \yii\db\Query())

    ->select('id, name')

    ->from('user')

    ->limit(10)

    ->all();


    $query->select('*')->from('user');


    $query->where('status=:status', [':status' => $status]);


    $query->where([

    'status' => 10,

    'type' => 2,

    'id' => [4, 8, 15, 16, 23, 42],

    ]);

    View Slide

  52. 52
    Database & Models
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Dealing with data
    { }
    Active Record
    namespace app\models;


    use yii\db\ActiveRecord;


    class Customer extends ActiveRecord

    {

    /**

    * @return string the name of the table associated with this ActiveRecord class.

    */

    public static function tableName()

    {

    return 'customer';

    }

    }

    View Slide

  53. 53
    Database & Models
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Dealing with data
    { }
    Active Record
    // Create a new record

    $customer = new Customer();

    $customer->name = 'Jason';

    $customer->save();


    // Find one record

    $customer = Customer::findOne(['id' => $id]);


    // Find many records

    $customers = Customer::findAll(['state' => $state]);

    // Advanced query

    $customers = Customer::find()

    ->select(['first_name'])

    ->where(['state'=>$state])

    ->orderBy(['city'=>SORT_ASC])

    ->limit(10)

    ->all();
    // Delete a record

    Customer::findOne(['id' => $id])->delete();

    View Slide

  54. 54
    Database & Models
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Dealing with data
    { }
    Active Record
    class Order extends ActiveRecord

    {

    public function getOrderItems()

    {

    return $this->hasMany(OrderItem::className(), ['order_id' => 'id']);

    }


    public function getItems()

    {

    return $this->hasMany(Item::className(), ['id' => 'item_id'])

    ->via('orderItems');

    }

    }


    $order = new Order();

    $items = $order->items;

    $orderItems = $order->orderItems;

    View Slide

  55. 55
    Database & Models
    Introduction to Yii2 - Jason Ragsdale
    !
    2
    Dealing with data
    { }
    Migrations
    class m101129_185401_create_news_table extends \yii\db\Migration

    {

    public function up()

    {

    $this->createTable('news', [

    'id' => Schema::TYPE_PK,

    'name' => Schema::TYPE_TEXT . ‘(50) NOT NULL',

    ]);

    }


    public function down()

    {

    $this->dropTable('news');

    }

    }
    $ yii migrate/create create_news_table
    $ yii migrate

    View Slide

  56. Q&A
    ?

    View Slide

  57. THANK YOU FOR WATCHING
    "

    View Slide

  58. 58
    #
    [email protected]
    twitter.com/jasrags
    linkedin.com/in/jasrags
    $
    %
    &
    Introduction to Yii2 -
    http://speakerrate.com/talks/39611-an-introduction-to-yiiframework-2

    View Slide