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."

C33a23d256e895d5cc6898ea3051528c?s=128

Jason Ragsdale

November 11, 2014
Tweet

Transcript

  1. 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!
  2. 3.

    3 Introduction Introduction to Yii2 - Jason Ragsdale ! •

    PHP >= 5.4.x • MVC (Model-Vew-Controller) • Extendable • Simple • High Performance 2 What is Yii2
  3. 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;
 }
  4. 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',
 ];
 }
  5. 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'),
 ];
 }
  6. 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;
 }
  7. 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'],
 ];
 }
  8. 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';
 ?>
 <h1><?= Html::encode($this->title) ?></h1>
 
 <p>Please fill out the following fields to login:</p>
 
 <?php $form = ActiveForm::begin(); ?>
 <?= $form->field($model, 'username') ?>
 <?= $form->field($model, 'password')->passwordInput() ?>
 <?= Html::submitButton('Login') ?>
 <?php ActiveForm::end(); ?>
  9. 11.

    What does it provide 11 Features Introduction to Yii2 -

    Jason Ragsdale ! 2 { } MVC Layouts <?php $this->beginPage() ?>
 <!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8"/>
 <?= Html::csrfMetaTags() ?>
 <title><?= Html::encode($this->title) ?></title>
 <?php $this->head() ?>
 </head>
 <body> <?php $this->beginBody() ?>
 <header>My Company</header>
 <?= $content ?>
 <footer>&copy; 2014 by My Company</footer>
 <?php $this->endBody() ?> </body>
 </html> <?php $this->endPage() ?>
  10. 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
 {
 }
  11. 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';
 }
  12. 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');
 }
  13. 15.

    { } Authentication & Authorization What does it provide 15

    Features Introduction to Yii2 - Jason Ragsdale ! 2
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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);
  19. 22.

    What does it provide 22 Features Introduction to Yii2 -

    Jason Ragsdale ! 2 { } RBAC 'components' => [
 'authManager' => [
 'class' => 'yii\rbac\PhpManager',
 // 'class' => 'yii\rbac\DbManager',
 ],
 ],
  20. 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);
  21. 25.

    What does it provide 25 Features Introduction to Yii2 -

    Jason Ragsdale ! 2 • APC • Db • Dummy • File • Memcache • Redis • WinCache • Xcache { } Caching
  22. 26.

    What does it provide 26 Features Introduction to Yii2 -

    Jason Ragsdale ! 2 • Data caching • Fragment caching • Page caching • HTTP caching { } Caching
  23. 27.

    What does it provide 27 Features Introduction to Yii2 -

    Jason Ragsdale ! 2 Data 'components' => [
 'cache' => [
 'class' => 'yii\caching\ApcCache',
 ],
 ], { } Caching
  24. 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
  25. 29.

    What does it provide 29 Features Introduction to Yii2 -

    Jason Ragsdale ! 2 Dependencies •Chained •Db •Expression •File •Tag { } Caching
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. 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
  32. 36.

    What does it provide 36 Features Introduction to Yii2 -

    Jason Ragsdale ! 2 { } RESTful Web Services
  33. 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
  34. 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
  35. 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
  36. 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
  37. 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),
 ];
 }
 }
  38. 42.

    What does it provide 42 Features Introduction to Yii2 -

    Jason Ragsdale ! 2 { } RESTful Web Services HATEOAS { "id": 100, "email": "user@example.com", // ... "_links" => [ "self": "https://example.com/users/100" ] }
  39. 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.
  40. 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";
 }
 }
  41. 46.

    What does it provide 46 Features Introduction to Yii2 -

    Jason Ragsdale ! 2 { } Testing & Gii DEMO
  42. 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/
  43. 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
  44. 49.

    49 Database & Models Introduction to Yii2 - Jason Ragsdale

    ! • DAO • Query Builder • Active Record • Migrations 2 Dealing with data
  45. 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();
  46. 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],
 ]);
  47. 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';
 }
 }
  48. 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();
  49. 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;
  50. 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
  51. 56.
  52. 58.

    58 # jrags@jasrags.net twitter.com/jasrags linkedin.com/in/jasrags $ % & Introduction to

    Yii2 - http://speakerrate.com/talks/39611-an-introduction-to-yiiframework-2