2012-02-23 23 views
1

私はCodeigniterでローカルに統計サイトを開発しています。Codeigniter:URLから変数を置く場所

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 

class Player extends CI_Controller 
{ 

    public function __construct() 
    { 
    parent::__construct(); 
    $this->load->model('player_model'); 
    $player_name = $this->uri->segment(3); 
    } 


    public function index() 
    { 
     echo "index"; 
    } 

    public function show_profile($player_name) 

    { 

     $data['player_stats'] = $this->player_model->get_stats($player_name); 
     $this->load->view('player/player_stats', $data); 
    } 

} 

?> 

これは動作しますが、私の質問は、$ PLAYER_NAME変数に関するされています。私は、次のローカルホスト/サイト名/プレーヤー/ show_profile /プレイヤー名

私が現在持っているようなURLを持っています。 __constructには$player_name = $this->uri->segment(3);がありますので、すべてのクラスメソッドで使用できます。これは私がそれをやるべきである方法ですか?

これは安全ですか?

答えて

4

拳は、上書きされ得るために起こっているので、コンストラクタで変数を割り当てるにはポイントがありません。 CIにlocalhost/sitename/player/show_profile/PlayerNameのようなURLを渡すと、メソッド(PlayerName)のgetをパラメータとして渡したものがあります。したがって、あなたの変数には

public function show_profile($player_name){ 

が設定されています。

第二に、私はピーターのに同意:

protected $player_name; 

をコントローラで、それがグローバルにアクセス作るため。しかし、私はコンストラクタで設定することに同意しません。このコントローラーに、その場所に変数を渡す別のメソッドがある場合は、そこに間違ったデータを取得します。

public function show_profile($player_name){ 

    $this->player_name = $player_name; 

    $data['player_stats'] = $this->player_model->get_stats($player_name); 
    $this->load->view('player/player_stats', $data); 
} 
+0

「$ this-> uri-> segment(3);」というのはどうでしょうか? – Motive

+0

私の投稿を更新しました。元のメソッドのプロトタイプである – Birdman

+0

に固執すれば、それは必要ありません。ああ、私はCIがそれらをメソッドに渡したことに気付きませんでした。知っておいてよかった!助けてくれてありがとう。 – Motive

1

$ player_nameというクラス変数を定義し、コンストラクタでsegment(3)に設定します。

class Player extends CI_Controller 

{

protected $player_name; 

public function __construct() { 
    parent::__construct(); 
    $this->load->model('player_model'); 
    $this->player_name = $this->uri->segment(3); 
} 

public function index() { 
    echo "index"; 
} 

public function (show_profile) { 

    $data['player_stats'] = $this->player_model->get_stats($this->player_name); 
    $this->load->view('player/player_stats', $data); 
} 

}

この方法は、クラス内の任意の場所の$ play_name変数にアクセスすることができるであろう。

また、$ this-> uri-> uri_to_assoc(n)メソッドを使用して設定されているかどうかを確認し、キー/値がisset()であるかどうかを確認することもできます。http://codeigniter.com/user_guide/ libraries/uri.html

すべてのピーター

関連する問題