jbyrd
jbyrd

Reputation: 5595

Defining base url constant instead of using base_url()?

Instead of calling the function:

base_url()

for every single link, would it make sense to define your base url in constants.php:

define('BASE_URL', 'http://mysite.com/');

and then use that constant so that the function call isn't potentially made many multiple times on a page?

Upvotes: 0

Views: 5681

Answers (2)

landons
landons

Reputation: 9547

Not entirely. You'll run into unexpected behavior if you use any of the following functions:

  • redirect()
  • site_url()
  • base_url()
  • form_open()
  • anchor()

That's not an exhaustive list--many other functions depend on the base url config setting. A better approach might be to use relative links instead, rather than hard-coding absolute URLs.

I, myself, have been tempted to use site_url() to define every link as a measure of paranoia (wondering to myself whether the URL structure will ever change). But really, undergoing a massive overhaul of the sitemap will create more difficult problems than just the links. For the sake of development, I now just use relative links where it makes sense.

Cheers!

Upvotes: 3

Colin Brock
Colin Brock

Reputation: 21575

In my opinion, I wouldn't worry about multiple calls to base_url() - I doubt it will have a significant impact on performance.

Additionally, I dislike the idea of using a constant because the base URL will essentially be defined twice, in two different places. Once in config.php and once wherever the BASE_URL constant would live. However, that's just my thought on it - perhaps someone else could make the case for it.

tl;dr I don't think multiple calls to base_url() is a problem and, in most cases, probably won't have a significant impact on performance.

Upvotes: 0

Related Questions