symfony askeet Day 13
タグ
- schema.ymlに追加する
- タグクラスを作る
schema.ymlに追加する。
今回は新しくQuestionTagテーブルを作ることにします。
なので、schema.ymlを書き直す。
場所: askeet2/config/schema.yml
ask_question_tag: _attributes: { phpName: QuestionTag } question_id: { type: integer, foreignTable: ask_question, foreignReference: id, primaryKey: true } user_id: { type: integer, foreignTable: ask_user, foreignReference: id, primaryKey: true } tag: varchar(100) normalized_tag: { type: varchar(100), primaryKey: true } _indexes: normalized_tag_index: [normalized_tag] created_at: ~
symfony propel-build-model symfony propel-build-sql symfony propel-insert-sql
タグクラスを作る
場所: askeet2/lib/Tag.class.php
<?php class Tag { public static function normalize($tag) { $n_tag = strtolower($tag); // 望まないすべての文字列を取り除く $n_tag = preg_replace('/[^a-zA-Z0-9]/','',$n_tag); return trim($n_tag); } public static function splitPhrase($phrase) { $tags = array(); $phrase = trim($phrase); $words = preg_split('/(")',$phrase,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $delim = 0; foreach($words as $key -> $word) { if($word=='"') { $delim++; continue; } if(($delim%2==1) && $words[$key-1]=='"') { $tags[] = trim($word); } else { $tags = array_merge($tags,preg_split('/\s+/',trim($word),-1,PREG_SPLIT_NO_EMPTY)); } } return $tags; } }
モデルを拡張する
場所: askeet2/lib/model/QuestionTag.php
<?php /** * Subclass for representing a row from the 'ask_question_tag' table. * * * * @package lib.model */ class QuestionTag extends BaseQuestionTag { public function setTag($v) { parent::setTag($v); $this->setNormalizedTag(Tag::normalize($v)); } }
テストデータを追加する。
場所: askeet2/data/fixtures/test_data.yml
QuestionTag: t1: { question_id: q1, user_id: dinotaro, tag: relatives } t2: { question_id: q1, user_id: dinotaro, tag: girl } t4: { question_id: q1, user_id: crazyup, tag: activities } t6: { question_id: q2, user_id: crazyup, tag: 'real life' } t5: { question_id: q2, user_id: dinotaro, tag: relatives } t5: { question_id: q2, user_id: dinotaro, tag: present } t6: { question_id: q2, user_id: crazyup, tag: 'real life' } t7: { question_id: q3, user_id: crazyup, tag: blog } t8: { question_id: q3, user_id: crazyup, tag: activities }
テストデータを読み込む前にキャッシュはクリアしておかないとハマるので今度から気をつける。
キャッシュをクリアしたらテストデータを読み込む。
symfony cc php batch/load_data.php