php.htaccessoopurlurl-masking

Can anyone suggest how to use OOP in PHP based on URL?


I am tired of making script based on pages and all. I do not want to do stuffs old ways. I want to learn OOP based on url. I know how to use .htacces for url masking and rewrite rule. But the thing is that when I forwarded all queries to a PHP page, I had to use switch case statement to include files. Like if query is p=profile then I need to include profile.php file either manually or by function. But I do not want do this type of things. I want to learn professional PHP so I can create webapps like wordpress and elgg and all. I've tried finding online tutorials about it but it didn't work for me.

I hope that at least one person will help me correct way.


Solution

  • Generally the parameters in the urls are used to call a respective class/function. Let say we have these urls:

    • example.com/index.php?controller=foo
    • example.com/index.php?controller=foo&function=edit
    • example.com/index.php?controller=bar

    At index.php you could start playing with includes like below:

    $controller = $_GET["controller"];
    include("controllers/{$controller}");
    $theClass = new $controller();
    

    Some web applications work with a "default funcion" that is triggered when a function is not specified in the url. For example, an index function:

    $function = $_GET["function"];
    if (empty($function))
        $function = "index";  // the default function to be called
    
    $theClass->$function();
    

    The Foo class can looks like this:

    class Foo{
    
        function index(){
            echo "hello index";
        }
    
    
        function edit(){
            echo "editing foo";
        }
    
    }
    

    Note: You can use $_SERVER['QUERY_STRING'] instead $_GET to give urls more "friendly".