Hamed Ghaderi
Hamed Ghaderi

Reputation: 98

Redirect Using PHP Method Chaining?

Let's say we want to redirect a user to a form page with some errors after submitting. I have this method in my controller.

return redirect('create')->withErrors($errors)->withInputs($inputs);

Now I have a helper function named redirect which returns a new Redirect object.

function redirect($fileName)
{
 return new Redirect($fileName);
}

and here is the sturcture of Redirect class

class Redirect
{

  public function __construct($fileName)
  {
    header("Location: " . $fileName);

    return $this;
  }


  public function withErros($errors)
  {
    session_start();
    $_SESSION['errors'] = $errors;

    return $this;
  }



  public function withInputs($inputs)
  {
    session_start();
    $_SESSION('inputs') = $inputs;

    return $this;
  }
}

The first chaining method (withErrors) runs correctly and I can show errors in my view. But the second one (withInputs) never runs. I think it's because of header function in PHP. Can somebody help me, please?

Upvotes: 0

Views: 287

Answers (1)

JOUM
JOUM

Reputation: 239

class Redirect
{
  protected $filename;
  public function __construct($fileName)
  {
      session_start();
      $this->filename=$filename;
  }
  public function __destruct()
  {
      $this->redirect();
  }
  public function withErros($errors)
  {
      $_SESSION['errors'] = $errors;
      return $this;
  }
  public function withInputs($inputs)
  {
      $_SESSION('inputs') = $inputs;
      return $this;
  }
  public function redirect(){
      header("Location: " . $this->filename);
      exit;
  }
}

This can be a solution.

Upvotes: 1

Related Questions