Frage

I'm trying to fetch control name from URL and match it with correct controller dynamically in index.php.

My app root : /localhost/app/index.php

So basically when i typed /localhost/app/index.php/home, trying to inlude home_controller.php. Here is code;

 $parts = array_slice(explode('/',$_SERVER["REQUEST_URI"]),3);
 if(file_exists(dirname(__FILE__)."/controllers/".$parts[0].'_controller.php'))
 {
    include dirname(__FILE__)."/controllers/".$parts[0].'_controller.php';
 }

It works fine if the app root depth is 3. It's broken when i changed app directory like localhost/first/second/app/index.php/home

Because it's explode by 3, $parts[0] is no longer "home" The question is how can i detect controller part in a more efficient way?

War es hilfreich?

Lösung

I used $_SERVER paht_info variable to calculate, controller part..

  $segments = array_slice(explode("/", $_SERVER["PATH_INFO"] ),1);

Zero index of $segment array is the controller part and the other parts is the function. Btw you need to check array boundries and whether path_info is set or not.

Andere Tipps

/localhost/app/index.php/home localhost/first/second/app/index.php/home sounds like its making your string the $parts[0] piece look like app/index.php/home which would be an invalid path. The only way to handle this is either explode that string with / as your delimiter or using the last one in the array as the location to compare or run through each. The concept of MVC though is the URL is always structured similar part one, home in this case required to determin controller, 2+ are usually used in refrence to parameters to a function from the controller

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top