LoginSignup
0
1

More than 5 years have passed since last update.

CodeIgniter URIパスとセグメントをごにょる

Last updated at Posted at 2017-02-01

こんなバグがあった

画面概要

  • 検索フォーム付きの一覧画面がある。

  • 仮にこのページのURLを「/seach/list」とする。

  • このページのページネーション用パラメータは
    /seach/list/2
    /seach/list/3
    というふうに後ろにつく。

  • 検索用パラメータはセッションに保存している。

  • 検索フォームにはこのようなリセットボタンがある。

reset.html
<button type="button" onclick="location.href='http://localhost/seach/list'">reset</button>

viewのソースは

reset_v.php
<button type="button" onclick="location.href='<?= base_url() . uri_string() ?>'">reset</button>

こんな感じ。

  • GET/POST両パラメータが何もない時に検索用セッションをクリアする。

何が起きたか

概要を見て「ん?」て思う人もいるでしょう、
2ページ目以降でリセットボタンが効かない!
効かない!効かない!何回クリックしても効かない!テストしろよ!

改善策

ページネーション用パラメータ消せばいいじゃん

まあそうなんですが、どうやって消そうか。
パスの最後の「/」より前が数値だったらそこ消そうか、is_numeric()使ったらいける。
いや、なんかそれはダサいぞ。

URIのセグメントというものにたどり着く。(これがかっこいいかは不明)
僕が説明するよりHPを見た方がわかりやすいと思う。
軽量PHPフレームワーク 'CodeIgniter' 徹底ガイド!:CI_URI

こうなった

reset_v_fix.php
<button type="button" onclick="location.href='<?= base_url() . ($this->uri->segment(3) ? str_replace($this->uri->slash_segment(3, 'leading'), '', uri_string()) : uri_string()) ?>'">reset</button>

第3セグメントが存在する場合はuri_string()から「/ + 第3セグメント」を消す。

ええ。それだけです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1