php のクラスを勉強中の者です。
勉強のため、簡単な掲示板をクラスを使用して作れないかと思い作ってみました。一応、書き込みができるよう動作はしています。
しかしクラスの使い方というか、使うための考え方というか本質的なところがあまりよくつかめていません。
全コードは下記です。
Bbs.php
php
1<?php 2class Bbs { 3 4 const BBS_FILE = './bbs.dat'; 5 6 private $name = ''; 7 private $comment = ''; 8 9 // 名前 10 public function setName($name) { 11 $this->name = (string)filter_var($name); 12 } 13 // コメント 14 public function setComment($comment) { 15 $this->comment = (string)filter_var($comment); 16 } 17 // エンコード 18 public static function encode($str) { 19 return htmlspecialchars($str, ENT_QUOTES, 'UTF-8'); 20 } 21 // データ書き込み 22 public function writeData() { 23 $data = []; 24 $data[] = self::encode($this->name); 25 $data[] = self::encode($this->comment); 26 $line = implode(',', $data)."\r\n"; 27 $fp = fopen( self::BBS_FILE, 'a' ); 28 fputs ( $fp, $line ); 29 fclose( $fp ); 30 } 31 // csvデータ内容を取得 32 public function getFile() { 33 if (file_exists( self::BBS_FILE ) === TRUE ) { 34 $fp = fopen( self::BBS_FILE, 'r' ); 35 $data = array(); 36 while ( $row = fgetcsv($fp) ) { 37 $data[] = $row; 38 } 39 fclose($fp); 40 } 41 return $data; 42 } 43 // 取得したcsvデータを表示 44 function showData() { 45 $data = $this->getFile(); 46 foreach ( $data as $row ) { 47 echo "<dt>投稿者:".$row[0]."</dt>"; 48 echo "<dd>コメント:".$row[1]."</dd>"; 49 } 50 } 51} 52?>
index.php
php
1<?php 2require_once 'class/Bbs.php'; 3 4$bbs = new Bbs(); 5 6foreach (['action', 'name', 'comment'] as $key) { 7 $p[$key] = (string) filter_input(INPUT_POST, $key); 8} 9 10if ( ($p['action'] == 'write' ) && isset($p['name']) && isset($p['comment']) ) { 11 $bbs->setName($p['name']); 12 $bbs->setComment($p['comment']); 13 $bbs->writeData(); 14} 15 16?> 17<form action="" method="post"> 18 <p>名前:<input type="text" name="name" /></p> 19 <p>コメント:<input type="text" name="comment" /></p> 20 <p><button type="submit" name="action" value="write">書き込む</button></p> 21</form> 22 23<dl> 24<?php 25$bbsData = $bbs->showData(); 26?> 27</dl>
間違えている部分、こうした方がよいなどといった部分がありましたらご指摘いただけますと幸いです。
また、下記の部分もクラスにすべきなのか(したかったらすればよいというのはそうなんですが)、するとしたらどのように書いたらよいのでしょうか。
php
1foreach (['action', 'name', 'comment'] as $key) { 2 $p[$key] = (string) filter_input(INPUT_POST, $key); 3} 4 5if ( ($p['action'] == 'write' ) && isset($p['name']) && isset($p['comment']) ) { 6 $bbs->setName($p['name']); 7 $bbs->setComment($p['comment']); 8 $bbs->writeData(); 9}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/04/25 05:52