Easy PHP MVC like Controllers!

Recently I was trying out jQuery’s AJAX wrapper, and wanted a way of calling multiple functions on a single PHP class in an MVC like way. This is the shortest simplest code I could come up with. Note this was just a test, so it’s not production proof, but feel free to take it and expand upon it…

First heres my index.html, using jQuery to populate 2

  • tags…
  • <head>
         <script type="text/javascript" src="scripts/jquery-1.3.2.js"></script>
        </head>
        <body>
         <script type="text/javascript">
          $(document).ready(function(){
           $("#userAgent").load("mvc.php?co=Test&ac=UserAgent");
           $("#hello").load("mvc.php?co=Test&ac=Hello&id=RossCoops");
          });
         </script>
         <ul>
          <li id="userAgent"></li>
          <li id="hello"></li>
         </ul>
        </body>

    And here’s my controllers/TestController.php…

    class TestController {
        function UserAgent() {
            echo $_SERVER['HTTP_USER_AGENT'];
        }
        function Hello() {
            echo "Hello ".$_GET["id"];
        }
    }

    And here’s the mvc.php code that ties it all together. First it takes the co param and adds ‘Controller’ to it; then it looks for a php file with that name in the controllers directory; then it creates an instance of that class and calls a method on it as named in the ac param…  

    $type = $_GET["co"]."Controller";
    require_once("controllers/".$type.".php");
    $controller = new $type;
    $controller->$_GET["ac"]();

    Short & sweet huh? Of course, the main drawback here is that all the controller methods cannot take params, but could get around this by using $_GET to pull params from the HttpRequest just like I get the id param in TestController.Hello(). You could go even further by using reflection to inspect a method’s params, and then pre-populate them before invoking the method from mvc.php… but that’s an exercise for another day!