The short answer for why you need to have a baseUrl()
facility is this:
Where the app is deployed should be a configuration issue, not a core application-functionality issue
In many - perhaps even most - cases, the base-url of the application will simply be $_SERVER['HTTP_HOST']
or $_SERVER['SERVER_NAME']
.
But that's not always the case.
The easiest example to consider is a standard website that has the usual pages:
http://example.com/
http://example.com/contact
http://example.com/about
// etc
Now you write (or buy or download as an OSS package) a blog application that you would like to deploy under the url:
http://example.com/blog
The blog could have links like:
http://example.com/blog/post/my-post-slug
http://example.com/blog/categories/some-category
//etc
All these links reside under /blog
.
The blog application itself should be concerned only with links/pages/routing inside the blog. Though your blog templates may very well contain header/footer links back to the rest of the site, the rest of the core blog application functionality should not have to know about of the rest of your site. Somehow, the blog application needs to know that when he generates links to blog posts and blog categories and all his other blog-related pages, they all must be prefixed with http://example.com/blog
.
The values $_SERVER['HTTP_HOST']
or $_SERVER['SERVER_NAME']
do not reflect this environment/deployment information. Configuring (!) the app with a base-url value and consistently using some kind of baseUrl()
function (that consumes this config) when generating links is a good way to keep your core application functionality focused on its own business and not on external deployment factors.