Where do you keep your redirect method?

Too much repetitive work to call header() and then die() [?] Every time you need to redirect to a different URL. So you probably have a function / method that looks like this:

 function redirect($url, $http_response_code = 302) { header("Location: ".$url, true, $http_response_code); die; } 

Where does this method live in your projects / framework?

It does not fit in any category. Wherever I say it is not. CodeIgniter (and Kohana) is placed inside the url helper class, but again, it doesn't feel good (along with methods like site_url() and base_url() ).

+4
source share
4 answers

I personally store it in the Response class (I have a static class that contains helper functions like this: redirect (), sendFile (), sendContent (), etc.).

If you don't have one, then you might have a request class (relevant to all aspects of the request, for example isAjax (), isCLI (), isSecure (), getServerSoftware (), getClientIP (), etc.). It is not 100% suitable here, but something is close.

+5
source

In my humble opinion, this code is too simple to write a function for it.

PS I think the default value should be 303 or 307.

+4
source

Of course, this should be in your Response class of your framework. If you use (one) front controller - my case - you have such a method in the front controller, and therefore it can be called from anywhere.

Update: The front script controller handles all requests (or most of them). The basic structure:

 <? // include you libraries // few common functions // get the request parameters // do some common work // include specific scripts to perform job depending on Url ?> 

For example, common work involves the ability to manage security permissions for all URLs in an application in one place, logging, connecting to a database, etc. Then you delegate the detailed work to certain scripts depending on the URL. Ok, where to put the redirect method? If you put it in any of the shared libraries included in the first part of the script or in common functions, it should be available for any method called later, especially in scripts that process specific URLs. Hope this clarifies.

I have not read all the details, but this link may help .

+3
source

I usually put it and some other different functions in a file called lib.php or misc.php in the root of my included directories. This may not be the most obvious location, but I always include a file in my controller with a comment explaining what it is.

EDIT:

A few other methods that go into this file for me are a few helper functions that I often use, for example:

 function def_value($arr, $k, $d = false){ return array_key_exists($k,$arr) ? $arr[$k] : $d; } 

These are usually very common methods that I use in my framework, but I do not want to require them in every file. Sometimes I include a redirect method as a static method in my Controller class.

+1
source

All Articles