忍者ブログ
[PR]
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。



2024/04/26 19:38 |
PHP1-86:クラスっぽい投稿フォーム作るその3

前回の続き。
テンプレを作成してバリデータと合わせました。

index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
<?php
 
//=========================================================================
//準備
    
    //根本のフォルダ
        $base_dir=dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR ;
        define('BASE_DIR',$base_dir);
    
    //必要なファイルをインクルード
        require_once('../../smarty/libs/Smarty.class.php');
 
//=========================================================================
//クラス
class HtmlForm{
    
    //-------------------------------------------------------------------------
    //インスタンス変数等
        
        //Smartyテンプレ、キャッシュ置き場
            private $smarty_template_dir='../templates/';
            private $smarty_compile_dir='../templates_c/';
        
        //エラーメッセージ入れ
            protected $error_message_array=array(
               'error_name_null'=>'氏名が入力されていません'
              ,'error_age_null'=>'年齢が入力されていません'
              ,'error_age_int'=>'年齢が正しくありません'
            );
        
    //-------------------------------------------------------------------------
    //コンストラクタ
    public function __construct(){
        
        //Smarty
            $this->smarty=new Smarty();
            $this->smarty->template_dir = $this->smarty_template_dir;
            $this->smarty->compile_dir  = $this->smarty_compile_dir;
        
        //実行メソッドを呼ぶ
            $this->init();
            exit();
    }
    
    //-------------------------------------------------------------------------
    //実行
    public function init(){
        
        //実行するメソッド選択
            if(isset($_REQUEST['form_input'])){
                $this->FormInput();
            }elseif(isset($_REQUEST['form_complete'])){
                $this->FormComplete();
            }else{
                $this->FormIndex();
            }
    }
    
    //-------------------------------------------------------------------------
    //表示
    public function view($template_file='index.html'){
        
        //変数アサイン
            //$this->dataに突っ込めば$dataで表示できる
                $this->smarty->assign('data',$this->data);
            //$_REQUESTは常時参照可能
                $this->smarty->assign('request',$_REQUEST);
        
        //表示
            $this->smarty->display($template_file);
            exit();
    }
    
    //-------------------------------------------------------------------------
    //投稿内容一覧画面
    public function FormIndex(){
        
        //表示内容取得
            $data_array=array();
            $tmp_array=file('data.txt',
               FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
            foreach($tmp_array as $data){
                $data_array[]=explode("\t",$data);
            }
            $this->data['data_array']=$data_array;
        //表示
            $this->view('form_index.html');
    }
    
    //-------------------------------------------------------------------------
    //フォーム入力画面
    public function FormInput(){
        
        //表示
            $this->view('form_input.html');
    }
    
    //-------------------------------------------------------------------------
    //フォーム入力完了画面
    public function FormComplete(){
        
        //入力値のバリデート
            $ret=$this->_FormValidate($_REQUEST);
            if(!$ret){
                $this->FormInput();
            }elseif($ret['error']){
                $this->data['error_message']=
                    $this->_FormSetErrorCode($ret['error']);
                $this->FormInput();
            }
            
        //保存
            $data=implode("\t",$_REQUEST)."\r\n";
            file_put_contents('data.txt',$data,FILE_APPEND);
        
        //表示
            $this->view('form_complete.html');
    }

    //=========================================================================

    //-------------------------------------------------------------------------
    //サブルーチン//入力値チェック
    public function _FormValidate($request_array){
        
        //引数
            if(!$request_array){return false;}
            $ret=array();
        
        //バリデート
            if(!$request_array['name']){
                $ret['error'][]='error_name_null';
            }
            if(!$request_array['age']){
                $ret['error'][]='error_age_null';
            }elseif(!is_numeric($request_array['age'])){
                $ret['error'][]='error_age_int';
            }
            
        //返却
            if($ret['error']){
                return $ret;
            }else{
                return true;
            }
    }

    //-------------------------------------------------------------------------
    //サブルーチン//エラーメッセージを入れておく
    public function _FormSetErrorCode($error_code_array=array()){
        
        //引数
            if(!is_array($error_code_array)){return false;}
        
        //返り値
            $ret=array();
        
        //各エラーコードに対してエラーメッセージを対応させる
            foreach($error_code_array as $error_code_val){
                $ret[]=$this->error_message_array[$error_code_val];
            }
        
        //返却
            return $ret;
    }//クラスのおわり
}

templates/form_index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
    <head>
        <title>投稿フォーム</title>
    </head>
    <body>
        <a href="./?form_input=1">発言する</a><br />
        
        {if $data.data_array}
            <table border=1>
                <tr>
                    <th>投稿日</th><th>氏名</th><th>年齢</th><th>発言</th>
                </tr>
                {foreach from=$data.data_array item=data_item }
                    <tr style="background:{cycle values='lightcyan,peachpuff'};">
                        <td>
                            {$data_item.0|date_format:"%Y-%m-%d %H:%M:%S"}
                        </td>
                        <td>
                            {$data_item.1|escape}
                        </td>
                        <td>
                            {$data_item.2|escape}
                        </td>
                        <td>
                            {$data_item.3|escape}
                        </td>
                    </tr>
                {/foreach}
            </table>
        {/if}
    </body>
</html>

templates/form_input.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
    <head>
        <title>投稿フォーム</title>
    </head>
    <body>
        {if $data.error_message}
            <div style="color:red;">
                {foreach from=$data.error_message item=error_message_val}
                    {$error_message_val|escape}<br />
                {/foreach}
            </div>
        {/if}
        
        <form method="POST" action="./?form_complete=1">
            氏名:
            <input type="text" name="name" size="20"
              maxlength="20" value="{$request.name|escape}" /><br />
            年齢:
            <input type="text" name="age" size="10"
              maxlength="4" value="{$request.age|escape}" /><br />
            発言:
            <input type="text" name="val" size="10"
              maxlength="4" value="{$request.age|escape}" /><br />
            
            <input type="submit" value="投稿する">
        </form>
    </body>
</html>

templates/form_complete.html
1
2
3
4
5
6
7
8
9
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
    <head>
        <title>投稿フォーム</title>
    </head>
    <body>
        投稿されました
    </body>
</html>


保存読み込み部分がアバウトすぎて、改行やタブを送信されたら死ぬというどうにもならないフォームです。
まあそこらへんどうにかしようとすればどうにでもなるのですが、面倒なので今回はパス。
DBに突っ込めば面倒なことを考える必要もないので、特に理由のない限り余計なことはせずにDBにしてしまいましょう。
それに保存用の関数などは直接書かず、それ用のクラスを作ってそちらに投げた方が色々と便利です。

バリデータの部分はもうちょっとerror_name_nullみたいなのを直接書かずにHtmlForm::error_message_arrayあたりをうまく利用して定義するべきなんですが、これもまあ面倒なのでいいや。
やりすぎてZend_Formみたいな意味不明状態になってもなんですし。

本当は投稿完了画面なんて要らなくて、インデックスに投稿完了した旨表示するだけでかまわないと思うのですが、何故か皆付けたがるので作っています。
まあそこらへんの遷移は好きなようにしてください。

こんなかんじで昔のよりちょっとだけソースが綺麗なような気がしないでもないフォームが完成しました。
見た目を変えたい場合は各HTMLファイルだけを触ればいいのでPHPの知識は不要となり、ロジックを触る場合はphpファイルを触ればいいのでデザインを壊す心配をする必要もありません。
いいことづくめですね。

まあ、といいつつプログラマがデザインの修正もさせられるのが世の常なんですが…

 

PR


2009/08/17 15:29 | Comments(0) | TrackBack() | PHP

トラックバック

トラックバックURL:

コメント

コメントを投稿する






Vodafone絵文字 i-mode絵文字 Ezweb絵文字 (絵文字)



<<PHP1-87:したらばBBS/NGワードまとめて削除1.2 | HOME | PHP1-85:クラスっぽい投稿フォーム作るその2>>
忍者ブログ[PR]