我正在本地开发Codeigniter的统计网站。我有一个像localhost / sitename / player / show_profile / PlayerName
的网址我目前有以下内容:
<?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变量。我在__construct中有$player_name = $this->uri->segment(3);
所以它可用于所有类方法。这是我应该这样做的吗?
这样安全吗?
答案 0 :(得分:4)
首先,在构造函数中分配变量没有意义,因为它会被覆盖。当你传递CI像localhost / sitename / player / show_profile / PlayerName这样的url时,任何传递方法的东西(即PlayerName)都被设置为参数。因此,你的变量在
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);
}
答案 1 :(得分: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-&gt; uri-&gt; uri_to_assoc(n)方法检查它是否设置,并检查键/值是否设置() http://codeigniter.com /user_guide/libraries/uri.html
彼得