Welcome Guest, Not a member yet? Register   Sign In
How to make these codes DRY?
#1

[eluser]solid9[/eluser]
Code:
//save username and password to cookie
public function save_cookie($user, $pass)
{
  $cookie = array(
      'name'   => 'user',
      'value'  => $user,
      'expire' => $this->cookie_life,
      'domain' => $this->cookie_dname,
      'path'   => '/',
      'prefix' => '',
      'secure' => FALSE
  );

  $cookie2 = array(
      'name'   => 'pass',
      'value'  => $pass,
      'expire' => $this->cookie_life,
      'domain' => $this->cookie_dname,
      'path'   => '/',
      'prefix' => '',
      'secure' => FALSE
  );
  
  $this->input->set_cookie($cookie); //save info to cookie
  $this->input->set_cookie($cookie2); //save info to cookie
}

Thanks in advanced.
#2

[eluser]jmadsen[/eluser]
try serializing your username & password and saving as the value.

any reason you are using cookies rather than sessions?
#3

[eluser]InsiteFX[/eluser]
You can also use json_encode and json_decode on the value.
#4

[eluser]solid9[/eluser]
@jmadsen
It's for remember_me login method.

@InsiteFX
What's the good reason of using json_encode?

Actually making it DRY it's very easy, I'll try to figure it out myself later when I have extra time.


#5

[eluser]InsiteFX[/eluser]
It's just another way that you can combine the user and password together into a string for the cookie value.

Most users use the serialize and unserialize methods to do it.

I wrote my own remember me methods that only use a hash key and the database which are update by a timeout.
#6

[eluser]boltsabre[/eluser]
You're passing 2 separate values to your function, but they are completely unique from each other. Why not combine into an array just pass one variable?

Perhaps you could do it like this:

Code:
//CODE UNTESTED, MAY BE BUGGY, BUT THIS IS THE JIST OF IT
//Just guessing that this stuff is happening in your controller, but put it wherever it really is
$user_pass = array ('user' => $user_whatever_it_is, 'pass' => $pass_whatever_it_is);
set_cookie($user_pass);
...

function set_cookie($input){
   if(is_array($input)){
      foreach ($input as $key => $value){
         $cookie = array(
            'name'   => $key,
            'value'  => $value,
            'expire' => $this->cookie_life,
            'domain' => $this->cookie_dname,
            'path'   => '/',
            'prefix' => '',
            'secure' => FALSE
          );
        $this->input->set_cookie($cookie); //save info to cookie
      }
   }
}

This technically, is keeping your code DRY, but...
Depending on what you want to do, this may not be the best set up. If you are setting up lots of cookies, then you may need create a more complex function (which could be isolated into it's own helper file).
For example, what if one cookie needs a different path, or something else. Then you may want to pass a multi dimensional array instead of an associate array, etc.




Theme © iAndrew 2016 - Forum software by © MyBB