Slide 1

Slide 1 text

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

Slide 2

Slide 2 text

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!

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

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;
 }

Slide 6

Slide 6 text

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',
 ];
 }

Slide 7

Slide 7 text

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'),
 ];
 }

Slide 8

Slide 8 text

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;
 }

Slide 9

Slide 9 text

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'],
 ];
 }

Slide 10

Slide 10 text

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


Slide 11

Slide 11 text

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() ?>

Slide 12

Slide 12 text

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
 {
 }

Slide 13

Slide 13 text

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';
 }

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

What does it provide 22 Features Introduction to Yii2 - Jason Ragsdale ! 2 { } RBAC 'components' => [
 'authManager' => [
 'class' => 'yii\rbac\PhpManager',
 // 'class' => 'yii\rbac\DbManager',
 ],
 ],

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

What does it provide 27 Features Introduction to Yii2 - Jason Ragsdale ! 2 Data 'components' => [
 'cache' => [
 'class' => 'yii\caching\ApcCache',
 ],
 ], { } Caching

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

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

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

{ } 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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

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),
 ];
 }
 }

Slide 42

Slide 42 text

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" ] }

Slide 43

Slide 43 text

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.

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

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";
 }
 }

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

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/

Slide 48

Slide 48 text

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

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

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();

Slide 51

Slide 51 text

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],
 ]);

Slide 52

Slide 52 text

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';
 }
 }

Slide 53

Slide 53 text

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();

Slide 54

Slide 54 text

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;

Slide 55

Slide 55 text

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

Slide 56

Slide 56 text

Q&A ?

Slide 57

Slide 57 text

THANK YOU FOR WATCHING "

Slide 58

Slide 58 text

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