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

Cakefest 2019 Basic Workshop

Cakefest 2019 Basic Workshop

Contents for the Basic Workshop. See https://cakefest.org

Avatar for Jorge M. González Martín

Jorge M. González Martín

November 07, 2019
Tweet

More Decks by Jorge M. González Martín

Other Decks in Programming

Transcript

  1. Basic Workshop 基本的なワークショップ • 2x3h sessions - 2x3hセッション • Starting

    from scratch - ゼロから始める • Slides and code - スライドとコード • Code - ソースコード: https:/ /bit.ly/34vTEho • Database - データベース: https:/ /bit.ly/2WF3niW • Slides - スライド: spearkerdeck
  2. About - 自己紹介 Jorge González @steinkelz • CakePHP Developer at

    CakeDC [email protected] https:/ /www.cakedc.com • CakeDCのCakePHP開発者 • Trainer at Cake Software Foundation https:/ /training.cakephp.org • Cake Software Foundationのトレーナー
  3. CakePHP Introduction はじめに • Setting up a development environment -

    開発環境のセットアップ • MVC • Example application - サンプルアプリケーション • Baking our application CRUD - アプリケーションを焼く
  4. Setup dev environment I 開発環境のセットアップ I • Requirements - 必要条件

    $ sudo apt install -y php-cli php-intl php-mbstring php-mysql php-sqlite3 mysql-server zip php-imap php-curl php-zip // setup composer 5
  5. Setup dev environment II 開発環境のセットアップ II • vagrant box https:/

    /www.cakedc.com/jorge_gonzalez/2018/01/17/using-a-vagrant-box-as-quick-environment-for-the-getti ng-started-with-cakephp-training-session 6
  6. Setup dev environment III 開発環境のセットアップ III • docker compose https:/

    /gist.github.com/steinkel/7a4860e2721872a28d7f6158e5bf3d89 7
  7. CakePHP application setup アプリケーションのセットアップ • Using composer + PHP builtin

    server • composer + PHPビルトインサーバーを使用する • Other alternatives - その他の選択肢 • Oven https:/ /github.com/cakedc/oven for 1 click setup - 1クリックセットアップ 8
  8. Composer • Create a CakePHP 4 project - CakePHP 4プロジェクトを作成する

    • https:/ /github.com/cakephp/app • composer install • run App\Console\Installer::postInstall $ composer create-project cakephp/app:4.x-dev cakefest2019 Installing... … Do you want to remove the existing VCS (.git, .svn..) history? [Y,n]? ←Y $ cd cakefest && cat composer.json {skeleton} 10
  9. CakePHP 4 project structure CakePHP 4プロジェクトの構造 bin composer.json composer.lock config

    index.php logs phpstan.neon phpunit.xml.dist plugins README.md resources src templates tests tmp vendor webroot 11
  10. Configuration - 構成 • Application class • CakePHP Bootstrap •

    config/bootstrap.php • config/app.php • The environment - 環境 • Configure default datasource via environment • 環境を介してデフォルトのデータソースを構成する • Command line - コマンドライン • Server / Container -サーバー/コンテナ • .env • Webserver - ウェブサーバー 13
  11. MVC CakePHP Reusability Model Table Entity Behavior View View Template

    Theme Layout Element Block Helper Controller Controller Action Component Other Cell, Mailer, Command Middleware CakePHP Concepts - コンセプト • Application level - アプリケーションレベル • Across applications: Plugin and Middleware - アプリケーション全体 14
  12. • dd() • Debugger • Logger • The query log

    - クエリログ • Step by step - ステップバイステップ Debug - デバッグする What's going on? - 何が起きているか? 15
  13. Build an IMAP ticket mailbox IMAPチケットメールボックスを作成する • Bake an admin

    CRUD • Explore CakePHP MVC - CakePHP MVCを調べる • Model: Tables & Entities - モデル:テーブルとエンティティ • Controllers - コントローラー • Views - ビュー
  14. $ mysql -uroot -e "CREATE DATABASE my_app; CREATE DATABASE test_myapp"

    $ mysql -uroot -e "GRANT ALL PRIVILEGES ON *.* to my_app@localhost identified by 'secret'" $ curl -L https:/ /bit.ly/2WF3niW |mysql -uroot my_app • Schema download URL: https:/ /bit.ly/2WF3niW •スキーマのダウンロードURL: https:/ /bit.ly/2WF3niW • Import schema •スキーマのインポート Database schema データベーススキーマ 17
  15. $ bin/cake bake all --everything Bake Shell ベイクシェル • Build

    a CRUD for our tables - テーブルのCRUDを構築する • Use an admin prefix - 管理者プレフィックスを使用する 19
  16. Generated Admin CRUD 生成された管理CRUD • Tables and Entities for each

    database table under src/model/{Table | Entity} src/model/{Table | Entity} の下の各データベーステーブルのテーブルとエンティティ • Controllers for each CRUD action under src/Controller src / Controllerの下の各CRUDアクションのコントローラー • Templates for each action under templates/{Controller}/{action} templates / {Controller} / {action}の下の各アクションのテンプレート 20
  17. • Table • Associations • Validation • Callbacks • Entity

    • Accessing fields - フィールドへのアクセス CakePHP model layer CakePHPモデル層 22
  18. • Initialization - 初期化 • “setTable()” • “setPrimaryKey()” • “setDisplayField()”

    • “addBehavior()” • Associations - アソシエーション • Say hi to strict_types - strict_typesに挨拶 CakePHP tables CakePHPテーブル 23
  19. • Access data as objects - オブジェクトとしてデータにアクセスする • set /

    get / has • accessible / hidden / virtual / dirty / errors • accessors / mutators • protected function _getX / protected function _setX 保護された関数_getX /保護された関数_setX CakePHP entities CakePHPエンティティ 24
  20. • Fix display fields - 表示フィールドを修正 • Ensure `role` is

    not accessible - 「ロール」にアクセスできないようにする • Normalize capitals for first and last name, like "JOHN smith" → "John Smith" 「JOHN smith」→「John Smith」など、姓と名の大文字を正規化します DIY: Entities DIY:エンティティ 25 {entity}
  21. • belongsTo • hasMany / hasOne • belongsToMany CakePHP associations

    CakePHPアソシエーション • Options - オプション • foreignKey, propertyName • conditions, joinType, sort • dependent • className 26
  22. • Create a new association to identify open tickets for

    a given user 特定のユーザーのオープンチケットを識別するための新しい関連付けを作成する DIY: CakePHP associations DIY:CakePHPアソシエーション 27
  23. • Validation when an Entity is created/modified: “validationDefault()” エンティティが作成/変更されたときの検証:“ validationDefault()”

    • Validation when an Entity is saved: “buildRules()” エンティティが保存されたときの検証:“ buildRules()” • newEntity() vs newEmptyEntity() CakePHP validation CakePHPの検証 28
  24. • Short format - 短い形式 • requirePresence, allowEmptyString, notEmptyString •

    inList, maxLenght, range, decimal, numeric, url, email, uuid, greaterThan, etc • Custom validation rules - カスタム検証ルール • Conditional validation rules - 条件付き検証ルール • Example: from/to email validation, subject has some #TICKET_ID 例:送信元/送信先の電子メール検証、件名には#TICKET_IDがあります Entity validation エンティティ検証 29
  25. • Password length > 8 characters for "admin" users 「admin」ユーザーのパスワードの長さ>

    8文字 • At least 1 number, 1 capital letter 少なくとも1つの数字、1つの大文字 • `role` is 'user' or 'admin' 「role」は「user」または「admin」です DIY: Entity validation DIY:エンティティの検証 30
  26. Authentication 認証 • New Plugins - 新しいプラグイン • Private Registration

    - プライベート登録 • Login - ログインする 32
  27. • cakephp/authentication https:/ /github.com/cakephp/authentication • Identification and authentication: Who are

    you? 識別と認証:あなたは誰ですか? • cakephp/authorization https:/ /github.com/cakephp/authorization • Authorization: Are you allowed? 許可:許可されていますか? New plugins 新しいプラグイン 33
  28. • New classes and interfaces - 新しいクラスとインターフェイス • Separation of

    concerns - 関心事の分離 • PSR-15 Middleware, it happens before your Controller logic PSR-15ミドルウェア、コントローラーロジックの前に発生 • Store identity in the Request - 要求にIDを保存する • AuthenticationService cakephp/authentication 34
  29. • Password • Others • Ldap • Token • JwtSubject

    • Callback Identifiers 識別子 35
  30. • Session (P) • Form • Others • Cookie (P)

    • HttpBasic (S) • HttpDigest (S) • Token (S) • Jwt (S) Authenticators 認証者 36
  31. • AuthenticationMiddleware::process() • AuthenticationService::authenticate() • First valid result wins -

    最初の有効な結果が勝つ • Persist the identity if not stateless - ステートレスでない場合はIDを保持します • Redirect based on unauthenticated or login redirect 認証されていないリダイレクトまたはログインリダイレクトに基づくリダイレ クト The authentication process 認証プロセス 37
  32. • Password based identifiers - パスワードベースの識別子 • Session and Form

    authenticators - セッション認証およびフォーム認証 Auth Configuration 認証設定 38
  33. • '/users/add' action - 「/ users / add」アクション • We'll

    restrict access to this action later このアクションへのアクセスは後で制限します Private registration プライベート登録 39
  34. • Let's get some more context before: 前にもう少しコンテキストを取得しましょう。 • Adding

    a login and logout actions to UsersController UsersControllerにログインアクションとログアウトアクションを追加する • Preparing a login template ログインテンプレートの準備 Next step would be: Login 次のステップ:ログイン 40
  35. Controllers and templates コントローラーとテンプレート • Actions - 行動 • Callbacks

    - コールバック • Request and Response - リクエストとレスポンス • Interacting with templates - テンプレートとの対話 • Creating basic forms - 基本フォームの作成 41
  36. • Glue Components, Models and Views together based on the

    current Request 現在のリクエストに基づいて、コンポーネント、モデル、ビューを一緒に接着する • Some interesting functions - いくつかの興味深い機能: • loadModel() • set(), render() • redirect() • Some available callbacks - 使用可能なコールバック • beforeFilter(), beforeRender() CakePHP controllers CakePHPコントローラー 42
  37. • PSR-7 Immutable objects - PSR-7不変オブジェクト • Wrappers providing functions

    to inspect the request and build the response 要求を検査して応答を作成する機能を提供するラッパー • ServerRequest • getAttribute(), getParam(), getQuery(), getData() • getSession() • Response • withType(), withHeader(), withFile(), withBody() • withCache(), withDisableCache() CakePHP request/response CakePHPのリクエスト/レスポンス 43
  38. • Debug form data if post 送信後のフォームデータのデバッグ • Log the

    login attempt to debug.log debug.logへのログイン試行のログ • Reject if not get/post get / postでない場合は拒否します DIY: Create users login action DIY:ユーザーのログインアクションを作成する 46
  39. • Access authentication results - 認証結果にアクセスする • Check identity -

    IDを確認する • Finish the login action - ログインアクションを完了する • Add logout - ログアウトを追加する Log the user in ユーザーをログインさせる 47
  40. IMAP service class IMAPサービスクラス • Disposable IMAP server - 使い捨てIMAPサーバー

    docker run -p "25:25" -p "143:143" linagora/james-jpa-sample:3.3.0 • Configure email (env) - 電子メールの構成(env) • Read latest emails - 最新のメールを読む 48
  41. 49

  42. 50

  43. • Configuration used for imap credentials - imapクレデンシャルに使用される構成 • composer

    require php-imap/php-imap • save email - メールを保存する Imap service class Imapサービスクラス 51
  44. Ticket Index チケットインデックス • Reading data - データの読み取り • Query

    object - クエリオブジェクト • Filtering - フィルタリング 52
  45. • Table::get • Table::find($type) , where $type is “all”, “list”,

    “custom” returns Query • ->first() returns Entity • ->toArray() returns [Entity] • ->count() returns int CakePHP reading data CakePHPの読み取りデータ 53
  46. • Lazy - レイジー • Some available Query functions are:

    - 利用可能なクエリ関数は次のとおりです。 • ->select(), ->where() • ->join(), ->contain() • ->order() • ->page(), ->limit(), ->offset() • ->group() CakePHP Query configuration CakePHPクエリ設定
  47. • Retrieve the first 20 non-admin users by creation date

    作成日までに管理者以外の最初の20人のユーザーを取得する DIY: Query example DIY:クエリの例 55 55
  48. CakePHP Query contain CakePHPクエリには • Short format - ショートフォーマット •

    $query->contain(['Alias1.Alias2']) • Long, flexible format - 長くて柔軟なフォーマット • $query->contain(['Alias1' => function ($q) { return $q->contain('Alias2'); }]) 56
  49. DIY: Create /tickets/my DIY:/ tickets / myを作成 • Display all

    tickets for the logged in user ログインしているユーザーのすべてのチケットを表示する 58
  50. Finalize /tickets/index / tickets / indexを確定します • Adding subject search

    - 件名検索の追加 • PRG • Display emails - メールを表示する 59
  51. • Reuse common Query configuration - 共通のクエリ構成を再利用する • Move logic

    to the model layer - ロジックをモデルレイヤーに移動する • public function findXXX(Query $query, array $options) : Query Custom finders カスタムファインダー 60
  52. DIY: Classify incoming emails DIY:受信メールを分類する • Detect ticket ID in

    the subject and auto-assign a ticket 件名のチケットIDを検出し、チケットを自動割り当て 61
  53. /tickets/add • Create new ticket/add action and template 新しいチケットの作成/アクションとテンプレートの追加 •

    Assign customer to user 顧客をユーザーに割り当てる • Ensure we keep previous users assigned too 以前のユーザーも引き続き割り当てられるようにする 62
  54. Sending emails メールを送信する • The Mailer class - メーラークラス •

    Customize emails - メールをカスタマイズする • Templates - テンプレート 63
  55. DIY: Send email to customer DIY:メールをお客様に送信します • Send new email

    on ticket creation チケット作成に関する新しいメールを送信する • Subject should have the ticket id, like "Ticket #12345 : Subject" 件名には、「チケット#12345:件名」などのチケットIDが必要です。 • Add a default layout - デフォルトレイアウトを追加する • Add an email template - メールテンプレートを追加する 64
  56. • addBehavior() • Callbacks • Mixin • Core Behaviors: •

    CounterCache, Timestamp, Tree, Translate Behaviors ビヘイビアー 65