14
レシピ本を書いて知った 小ネタ 3 長谷川智希 @tomzoh http://sozai.7gates.net/ 無料素材倶楽部

CakePHP X'mas Presentation

Embed Size (px)

Citation preview

Page 1: CakePHP X'mas Presentation

レシピ本を書いて知った 小ネタ3つ長谷川智希 @tomzoh

http://sozai.7gates.net/ 無料素材倶楽部

Page 2: CakePHP X'mas Presentation

自己紹介長谷川智希

デジタルサーカス(株)副団長CTO

Web/スマホアプリ開発

@tomzoh facebook.com/hasegawa.tomoki

Page 3: CakePHP X'mas Presentation

小ネタ1

Page 4: CakePHP X'mas Presentation

小ネタ1.

HABTM

記事 Article articles

タグ Tag tags

結合テーブル

class Article extends AppModel { public $hasAndBelongsToMany = array(‘Tag’) }

Has And Belongs to Many n:nの結合を表現するアソシエーション

Page 5: CakePHP X'mas Presentation

小ネタ1.

HABTM

「2つのテーブルの複数形を接続した名前」

articles_tags? tags_articles?どっち側から見て?

なんとなく作ってエラーメッセージ見て修正。

記事 Article articles

タグ Tag tags

結合テーブル ?

Page 6: CakePHP X'mas Presentation

小ネタ1.

HABTM記事

Article articles

タグ Tag tags

結合テーブル articles_tags

結合テーブルの名前は…

アルファベット順!

Page 7: CakePHP X'mas Presentation

小ネタ2

Page 8: CakePHP X'mas Presentation

小ネタ2.

組込定数開発環境のパスとURL、本番環境のパスとURL。

core.phpで定義してた。

switch(getenv(‘SERVER_NAME’)){ case ‘dev.xxx.com’: define(‘PROJECT_ROOT’, ‘/var/www/xx/app/‘); ! default: define(‘PROJECT_ROOT’, ‘/var/www/yy/app/‘); !}

Page 9: CakePHP X'mas Presentation

小ネタ2.

組込定数便利な組込定数/メソッドがありました…。

APPappディレクトリのパス /path/to/project/app/

ROOTappディレクトリを含むパス /path/to/project

WWW_ROOTwwwrootディレクトリのパス /path/to/project/app/webroot/

Router::fullbaseUrl() Configure::read(‘App.fullBaseUrl)

ドキュメントルートのURL http://www.example.com

Page 10: CakePHP X'mas Presentation

小ネタ3

Page 11: CakePHP X'mas Presentation

小ネタ3.

非正規フィールドの自動更新ユーザ User、コメント Comment があるシステム。

ユーザのコメント数を毎回計算すると大変なのでUser.comment_countを作る。

CommentのafterSave()あたりで計算したくなるよね。

イベントシステムを使おう!

Page 12: CakePHP X'mas Presentation

小ネタ3.

非正規フィールドの自動更新ずばりそれをサポートする機能がありました。

belongsToのオプション。相手のテーブルの[テーブル名]_commentが更新される。

ユーザ User

comment_count

コメント Comment

Page 13: CakePHP X'mas Presentation

小ネタ3.

非正規フィールドの自動更新class Comment extends AppModel { public $belongsTo = array( 'User' => array( 'counterCache' => true, 'counterScope' => array( 'Comment.is_deleted' => false ), )); }

こうやって指定

条件指定も可能

Page 14: CakePHP X'mas Presentation

ご静聴ありがとうございました。

@tomzoh facebook.com/hasegawa.tomoki