CodeIgniter从方法位置获取URL变量?

时间:2018-01-06 19:41:41

标签: php codeigniter

我正在使用代码点火器,我的网址结构如下所示:

http://localhost:8888/project/register

在这种情况下注册是控制器。

我正在尝试将ID传递给此URL,如下所示:

http://localhost:8888/project/register/1234以便我可以在我的控制器中使用此值。

我遇到了一个问题,试图解决这个问题,因为这个ID的位置是指控制器中方法的名称。

是否可以在此位置添加值而不考虑其方法,或者我是否需要执行以下操作: http://localhost:8888/project/register?code=1234

尝试像这样访问它:$registerPin = $this->common->nohtml($this->uri->segment(2));

更新

作为黑客的解决方法,我这样做了..还有更好的方法吗?

网址:http://localhost:8888/project/register/c/1234

/**
 * Pass our signup code for demo purposes
 */
public function c(){

    // Did we come here from a Sign-up Pin?
    $registerPin = $this->common->nohtml($this->uri->segment(3));

    if($registerPin){
        $this->session->set_userdata(array(
            'registerPin'  => $registerPin
        ));
    }

    // Redirect to register
    redirect(site_url("register"));

}

public function index()
{   
 echo $this->session->userdata('registerPin');
}

1 个答案:

答案 0 :(得分:0)

一种解决方案是使用Controller的_remap功能,虽然我没有按照您打算使用它的方式使用它。 (希望它有效)

请参阅:https://www.codeigniter.com/userguide3/general/controllers.html#remapping-method-calls

<?php 

class Register extends MY_Controller{

    public function __construct()
    {
        parent::__construct();
    }

    // -----------------------------------------------------------------------

    /**
     * Controller remapping
     */
    public function _remap( $method, $params = [] )
    {
        if( is_numeric( $method ) )
        {
            $this->index( $method );
        }
        else
        {
            $this->$method();
        }
    }

    // -----------------------------------------------------------------------

    /**
     * Index method
     */
    public function index( $num )
    {
        # code...
    }

    // -----------------------------------------------------------------------
}

另一种解决方案是使用URI路由。

请参阅:https://www.codeigniter.com/userguide3/general/routing.html

$route['register/(:num)'] = 'register/index/$1';

这些示例中的任何一个都不能完全正常运行,但应该接近您的需要。

相关问题