下記部分のget_count()
関数はコントローラーではなく、プレゼンター
に組み込むのが妥当かと思います。
php
1<p class="ico_heart vote_01"><?= get_count('vote_01') ?></p>
2<p class="btn_vote" id="vote_01"></p>
ルーター設定
下記、アクションコントローラーに組み込む例です。
ここでは、便宜上コントローラー名をsomething
としています。
適宜変更してください。
http://ドメイン/vote
でsomething
コントローラークラスのvote
アクションメソッドを実行するようにルーターを設定します。
php
1// app/config/routes.php
2return array(
3 'index' => 'something/index',
4 'vote' => 'something/vote',
5 ...
コントローラー
コントローラーを下記のように設置します。
下記はFuelPHPコアのTemplate機能
を使用していますが、好みで変更してください。
php
1// app/classes/controller/something.php
2class Controller_Something extends \Controller_Hybrid
3{
4 public $template = 'template/simple';
5
6
7 public function before ()
8 {
9 parent::before();
10 $this->template->header = \View::forge('template/header');
11 $this->template->footer = \View::forge('template/footer');
12 }
13
14 public function action_index ()
15 {
16 $this->template->contents = \Presenter::forge('index/index');
17 }
18
19 public function get_vote ()
20 {
21 $this->format = 'json';
22
23 $file = \Input::get('file', '初期ファイル名').'.dat';
24 $count = \Input::get('count', 1);
25
26 try {
27 // 投票書込み
28 \File::update('data/', $file, $count);
29 }
30 catch (\Exception $e) {
31 // エラー処理
32 }
33
34 $resp = array('success' => true, 'count' => $count);
35
36 return $this->response($resp)->send();
37 }
38}
プレゼンター
そして、下記のパスにプレゼンターを設置します。
php
1// app/classes/presenter/index/index.php
2class Presenter_Index_Index extends \Presenter_Base
3{
4 public function view () {}
5}
プレゼンター基底クラス
投票カウンター関数(get_count())
は、他の\View
でも使いまわしができるように、共通プレゼンターを作成して設置します。
php
1// app/classes/presenter/base.php
2class Presenter_Base extends \Presenter
3{
4 public function before ()
5 {
6 // 投票カウンター
7 \View::set_global('get_count', function ($file)
8 {
9 return $this->_getCountVote($file);
10 }, false);
11 }
12
13 protected function _getCountVote ($file)
14 {
15 //$filename = 'data/'.$file.'.dat';
16 //$fp = @fopen($filename, 'r');
17 //if ($fp) {
18 // $vote = fgets($fp, 9182);
19 //} else {
20 // $vote = 0;
21 //}
22
23 // ↓↓↓ FuelPHPらしくちょっと修正 ↓↓↓
24
25 $filename = 'data/'. $file .'.dat';
26
27 if (! \File::exists($filename)) {
28 return 0;
29 }
30
31 try {
32 // 投票値取得
33 return (int) \File::read($filename, true);
34 }
35 catch (\Exception $e) {
36 // エラー処理
37 }
38
39 return 0;
40 }
41}
ビュー
あとは、\Viewグローバル関数
を読み込むために下記のようにget_count()
の前に$
を付けます。
php
1<p class="ico_heart vote_01"><?= $get_count('vote_01') ?></p>
2<p class="btn_vote" id="vote_01"></p>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/30 00:44