开发者

how to pass a value to model function in code igniter

开发者 https://www.devze.com 2023-03-20 06:15 出处:网络
I want to pass a user id value in variable $userID, to a function in a Model class Cl开发者_C百科ientmodel.The function is get_username(), now in a model do I have to define that function to accept a

I want to pass a user id value in variable $userID, to a function in a Model class Cl开发者_C百科ientmodel. The function is get_username(), now in a model do I have to define that function to accept a variable as a parameter? so.. get_username($userID)? Just want to know how is the recommended way in code igniter?

Thanks!

tariq


That really depends on what you use the model for. Most of the time, it will make sense to have a parameter to the method and use that every time:

// Model
function get_username($userID)
{
    // do something with $userID
}

// Controller
$this->some_model->get_username($some_id);

On the other hand, sometimes it makes sense for the Model to be "stateful" -- do you have one userID per controller? Will it ever be more than one? Do you need the userID in a large number of methods of that model? Then maybe this will make sense instead:

// Model
function set_userid($userID)
{
    $this->userID = $userID;
}

function get_username()
{
    // do something with $this->userID
}

// Controller
$this->some_model->set_userid( $some_id );
$this->some_model->get_username();

Other times, you may have one userID which you plan on using over and over, but sometimes you need to use another value, that is when default arguments come into play:

// Model
function set_userid($userID)
{
    $this->userID = $userID;
}

function get_username( $userID = NULL )
{
    if( $userID === NULL ) $userID = $this->userID;
    // do something with $userID (not $this->userID)
}


// Controller
$this->some_model->set_userid( $some_id );
$this->some_model->get_username();


The solution is not Codeigniter specific in any way, it's just basic PHP. Your model is a class, and get_username() is a function that takes arguments.

The most basic way to do it is this:

// Model
function get_username($userID)
{
    // do something with $userID
}

// Controller
$this->some_model->get_username($some_id);

Make sure you read about default arguments so you can decide what to do if $userID is not passed (you may not need a default here though), and make sure you check that the value is valid.

0

精彩评论

暂无评论...
验证码 换一张
取 消