0

In many controllers, I need to verify if an object (ID passed in URL) exists.

I actually have this skeleton for each controller :

public function my_page($id){

$object = $this->Object_model->getObject($id);

if($object == NULL){ // If id mentions a non-existant object, redirect to home
  redirect("home");
}

/** MYCONTROLLER **/
}

Is it the good way, the cleanest way to do that ?

Some other options are helpers / model methods / controller methods... I don't know what is the PHP philosophy for that.

nlassaux
  • 2,335
  • 2
  • 21
  • 35

3 Answers3

0

Don't mix your controllers with the task to route the application. First you route and then you instantiate one of your controllers according to the given results.

Maybe this answer about routers clarifies what I mean: How does MVC routing work?

Community
  • 1
  • 1
chrisp
  • 569
  • 4
  • 24
  • I don't see how I can do the control if ID exists with CI routing. Route sends a visitor with URL to my controller, I can't use any function or method except a regex between URL reading and the send to Controller – nlassaux Jul 20 '14 at 18:01
0

The answer of your DB query is a boolean, so you must check if it's FALSE, and not NULL

public function my_page($id){

  $object = $this->Object_model->getObject($id);

  if($object === FALSE){
    redirect("home");
  }

  /** MYCONTROLLER **/
}
Adrian Tombu
  • 696
  • 6
  • 11
0
    if ( ! $object = $this->Object_model->getObject( $id ) ) {
        redirect( "home" ) ;       }

better would be Object_model always returning something whether there was an error or not.

   $object = $this->Object_model->getObject( $id ) ;

   if ( $object->errorFlag == true ) {
   redirect( "sorry/" . $object->errorMsg ) ; } 
cartalot
  • 3,147
  • 1
  • 16
  • 14