Say I have the url /product/view/1
which means I have the method in my product controller class:
function view($id)
{
// Do s开发者_StackOverflow社区omething here
}
How do I get it to graciously fail if someone goes to /product/view
?
Currently I'm getting two error messages, one saying Missing argument 1 for Budget::view()
and one saying Undefined variable: id
both of which I would expect, but obviously I'd rather provide my own one.
Two ways,
Option one: Give a default value for the $id
variable by saying
function view($id = '')
{
// Do something here and test if it's empty
}
This is what is traditionally done with optional parameters for functions in PHP
Option two: Rather than passing in the URI segment to the function as a parameter, you could alternatively get it using the URI helper (autoloaded by default)
function view()
{
$id = (int) $this->uri->segment(3);
// Do something here
}
Then you could test whether the id is set and do it from there
if your controller is product, and method is view
...
function view ( $id = null ) {
// set graciously failing if $id = null to avoid error
// and make happend what you want
....
}
...
Don't know about any CodeIgniter specifics, but you can always redirect with .htaccess
and mod_rewrite
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/product/view$
RewriteRule ^(.*)$ http://www.example.com/your-error-document [R=301,NC,L]
function view($id = false)
{
if ($id===false) {
//show error
show_error('your error');
//or redirect
}
// Do something here
}
精彩评论